2017-01-20 162 views
0

目的:检查用户输入()

如果用户输入bfloat打印张数floor(b), round(b), ceil(b)

其他打印scanf error: (%d)\n

该指令(由我们的老师提供)有这样的代码,我不明白。

这里是我的代码: `

#include <stdio.h> 
#include <math.h> 

int main(void) { 
    float b; 
    printf("Eneter a float number"); 
    int a=0; 
    a=5; 
    a=scanf("%d", &b); 
    if (a=0) 
    { 
     printf("scanf error: (%d)\n",a); 
    } 
    else 
    { 
     printf("%g %g %g",floor(b), round(b), ceil(b)); 
    } 
    return 0 
} 
+0

也许读这可能有助于 - [man scanf](https://linux.die.net/man/3/scanf) –

+2

您不能使用“%d”作为浮点数。 – stark

+0

@EdHeal:也可以用'-Wall'编译(或者等价的,取决于编译器)。 GCC'-Wall'会挑出'a = 0'和'%d'错误。 –

回答

4

错误#1

if (a=0) // condition will be always FALSE 

必须

if (a==0) 

或更好

if (0 == a) 

错误#2

scanf("%d", &b); // when b is float 

代替

scanf("%f", &b); 

UPDATE:

实际上,对于检查scanf结果的情况下,我个人更喜欢使用!=与输入的值的数量与最后的scanf。例如。如果需要两个逗号隔开的整数,继续计算片段可以是:

int x, y; 
int check; 
do{ 
    printf("Enter x,y:"); 
    check = scanf("%d,%d", &x, &y); // enter format is x,y 
    while(getchar()!='\n'); // clean the input buffer 
}while(check != 2); 

这个循环会重新要求输入,如果check2,即如果是0时(甚至第一个值是不正确,如abc,12 ),或者如果它是1(当用户忘记逗号或逗号后面输入的不是数字,如12,y

+1

尤达不是更好(现代编译器可以挑这个问题) –

+0

@EdHeal你已经证明他的老师是愚蠢的标准的基础上但他并不是因为他使用编译器而不是仅仅阅读这些标准。 –

+0

为什么'0 == a'比'a == 0'好? – thiagowfx

1

代码的整改意见 - 也可以在这里 - http://ideone.com/eqzRQe

#include <stdio.h> 
#include <math.h> 

int main(void) { 
    float b; 
// printf("Eneter a float number"); 
    printf("Enter a float number"); // Corrected typo 
    fflush(stdout); // Send the buffer to the console so the user can see it 
    int a=0; 
// a=5; -- Not required 
    a=scanf("%f", &b); // See the manual page for reading floats 
    if (a==0) // Need comparison operator not assignemnt 
    { 
     printf("scanf error: (%d)\n",a); // A better error message could be placed here 
    } 
    else 
    { 
     printf("%g\n", b); // Just to check the input with ideone - debugging 
     printf("%g %g %g",floor(b), round(b), ceil(b)); 
    } 
    return 0; // You need the semi-colon here 
} 

对于VenuKant萨胡益处

返回值

这些函数返回成功匹配 和分配的输入项目数,其可以是较少在 的事件甚至为零比规定,或早期匹配失败。

如果在第一次成功转换或发生匹配故障时 之前达到输入的结尾,则会返回值EOF。如果发生读取错误,EOF为 也会返回,在这种情况下,流的错误 指示符(请参阅ferror(3))已设置,并且errno设置为 表示错误。

+0

请告诉我,如果我是对的。 'scanf(“%f”,&b)'是一个函数,运行后返回1或0,1表示运行,0表示不运行。我可以认为它是一个布尔值吗? –

+0

否 - 因为如果您在上面阅读它可以返回EOF –