使用 scanf() 检查 C 中的用户输入

标签 c if-statement input

目的:

如果用户输入 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
}

最佳答案

错误#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/

相关文章:

c - 如何写入来自父进程的 getpass() 输入?

html - 使用 HTML/CSS 覆盖浏览器表单填写和输入突出显示

c - 如何在 jni 中访问传递给 c 的 JSON 数据?

javascript - 谷歌API : Infowindow Content Issue

javascript - 使用 jQuery 检测元素是否具有某种样式属性

input - 如何限制输入整数从 1 到 9

c++ - sscanf 从八进制转换 : How does it know?

c - 使用系统调用读写

c++ - 将无符号整数与负文字进行比较

php - 如果元素使用特定的浏览器,有没有办法改变元素的值?