目的:
如果用户输入 b
是 float
数字打印 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
}
最佳答案
错误#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);
更新:
实际上,对于检查 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);
如果 check
不是 2
,即如果它是 0
(即使第一个值是不正确,例如 abc,12
) 或者如果它是 1
(当用户忘记逗号或在逗号后输入的不是数字时,例如 12,y
关于使用 scanf() 检查 C 中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41769502/