c - C语言中如何判断是否为数字

标签 c validation input

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

int main()
{
    float a;
    float b;
    float gr;

    gr = (1 + sqrt(5)) / 2;
    gr = floorf(gr*1000 + 0.5) / 1000;  
    printf("Enter two numbers: ");
    scanf("%f %f", &a, &b);


    if(isalpha(a) || isalpha(b))
    {
        printf("\nInvalid input.\n");
        exit(0);
    }

    float result = a/b;

    if(floorf(result*1000+0.5)/1000 != gr)
    {
        float temp;
        temp = a;
        a= b;
        b = temp;
        result = a/b;
    }

    result = floorf(result*1000+0.5)/1000;

    if(result == gr)
    {
        printf("\nGolden ratio!\n");
    } else if(result != gr) {
        printf("\nMaybe next time.\n");
    }
    return 0;

}

除了“if(isalpha(a) || isalpha(b))”部分之外,一切正常。 我想让程序检查用户输入是否是数字 但是当我运行它并输入 a 和 b 时,它会打印出“也许下次”, 不是“无效输入”... 任何帮助将不胜感激!!

最佳答案

假设您输入 2 个字母,而不是数字:

Enter two numbers: x y

因为您使用 %f,所以 scanf 需要数字。但由于第一个字母是x,所以它会立即停止。 ab 均保持不变。这意味着两件事:

  • 由于 ab 未初始化,比较它们的值没有任何意义。

  • ab 上使用 isalpha 根本没有任何意义,因为该函数需要一个字符,而不是 float

幸运的是,scanf 返回成功转换的数量。因此,将您的测试更改为

printf("Enter two numbers: ");    
if(scanf("%f %f", &a, &b) != 2) // 2 conversions expected
{
    printf("\nInvalid input.\n")

关于c - C语言中如何判断是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44241407/

相关文章:

python - 密码学:将 C 函数转换为 python

c - 在运行时初始化二维数组并允许用户输入

ruby-on-rails - rails 2.3.8 : Validating an object before save shows previous references and not updated ones

ruby-on-rails - 如何验证 RoR 中的用户输入?

c - 我无法访问结构内部的数组

forms - Angular 2 - 使用带有可选字段的 ngControl

c# - 系统.InvalidOperationException : Unable to generate a temporary class (result=1)

C++: ifstream::getline 问题

css - 动画提交按钮

c - 难以理解 fork() 和进程树