isdigit()函数doens&#t; t?

时间:2015-04-12 00:32:39

标签: c

这是我的代码:

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

int main(void)
{
    int limit;
    float sum=0;
    while(1){
        printf("Enter the limit L: );
        scanf("%d",&limit);
        if(!isdigit(limit))
            break;
        for(int i=0;i<limit;i++){
            sum+=(float)1/(i+1);
        }
        printf("Sum of the initial %d term(s): %f\n",limit,sum);
        sum=0;
    }
    return 0;
}

如果输入整数,则该程序计算从n = 1到n = L(从用户获得输入)的1 / n的sigma,并在输入非数字字符时退出。但似乎这个程序并没有像我预期的那样工作: (我使用LLVM编译器)

wak@waksys:~$./a.out
Enter the limit L: 5000
wak@waksys:~$

程序结束时没有产生任何结果......所以我认为这部分可能存在一些问题:

if(!isdigit(limit))
    break;

所以我尝试删除&#39;!&#39;。

if(isdigit(limit))
    break;

然后我重新编译并执行了它。它似乎按预期工作但是......

Enter the limit L: 5000
Sum of the initial 5000 term(s): 9.094514
Enter the limit L: 1000
Sum of the initial 1000 term(s): 7.485478
Enter the limit L: 1
Sum of the initial 1 term(s): 1.000000
Enter the limit L: e
Enter the limit L: Sum of the initial 1 term(s): 1.000000
Enter the limit L: Sum of the initial 1 term(s): 1.000000
Enter the limit L: Sum of the initial 1 term(s): 1.000000
Enter the limit L: Sum of the initial 1 term(s): 1.000000
Enter the limit L: Sum of the initial 1 term(s): 1.000000
Enter the limit L: Sum of the initial 1 term(s): 1.000000
....
....

是的......它不会以无限循环结束(实际上,它是通过删除&#39;而预期的结果!&#39;)

所以似乎isdigit()函数判断5000,1000这样的数字不是整数。或者我的代码有问题吗?

3 个答案:

答案 0 :(得分:3)

isdigit测试字符是字符集中的数字。也就是说,&#39; 1&#39;是一个数字,但是&#39; x&#39;不是。 &#39; 1&#39;数字值为整数(在ascii中,它是49)当你输入5000时,scanf将其转换为整数值,5000(mod 256)可能不是&#39; 0&#39;,&#39; 1&#39;,&#39; 2&#39;,...,或&#39; 9&#39;在本地字符集中。而不是使用isdigit,检查scanf是否返回1.

答案 1 :(得分:2)

isdigit()检查单个字符的值,看它是否为数字('0''9'之间的字符)。

它不用于检查scanf("%d", ...)是否已成功扫描整数值。如果要检测是否已成功读取整数值,请检查scanf()的返回值。这样做根本不涉及使用isdigit()

答案 2 :(得分:0)

isdigit确实需要int作为输入,但这只是因为它可以处理EOF之类的不适合的事情。 unsigned char

isdigit用于检查特定字符是否是您的平台使用的编码中的数字。

它不是按照您使用它的方式使用的,所以不要期待从中得到合理的东西。