【问题标题】:Error message: if the number is not integer but float错误信息:如果数字不是整数而是浮点数
【发布时间】:2020-06-19 05:30:48
【问题描述】:

为什么我放一个浮点数没有出现错误?

int m;
if(scanf("%d%",&m)!=1)
{
    printf("Error\n");
    exit(1);
}

【问题讨论】:

  • 取决于“float”的确切给出方式:例如,“1.2”可以(正确)视为整数输入(即“1” - 忽略其余部分);但是,“.123”很可能会失败。
  • 也许这篇文章:C-Checking if input (float) is purely integer or float 会有所帮助?

标签: c if-statement scanf


【解决方案1】:

因为%d 将消耗所有十进制数字,直到第一个非十进制数字。因此,如果您输入"50.5"m 的值将是 50,而字符 ".5" 将保留在缓冲区中未读。

有许多可能的解决方案。这是一个:

int m ;
double fm ;

if( scanf("%f%",&fm) != 1 || 
    modf( fm, &m) != 0 )
{
    printf("Error\n");
    exit(1);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    相关资源
    最近更新 更多