Online Compiler C

#include <stdio.h> int is_digit(char c){ if((c=getchar)==1){ return 1; }else return 0; } int main(void) { int c; int count = 0; while ((c = getchar()) != EOF && c != '.') { if (is_digit((char)c)) { ++count; } } printf("%d", count); return 0; }
这段代码试图统计输入中数字字符的个数,直到遇到句点或文件结束符。但 `is_digit` 函数的实现有严重错误。

- 在 `is_digit` 函数中,你写的是 `(c=getchar)==1`,这实际上从输入读取了一个新字符,而不是判断传入的字符 `c` 是否为数字。而且 `getchar` 返回的是字符的ASCII码,数字字符'0'到'9'的ASCII码是48到57,不是1。所以这个条件永远不会成立,函数总是返回0,导致计数永远为0。

- 正确的思路应该是:判断传入的字符 `c` 是否在字符'0'到'9'之间,即 `c >= '0' && c <= '9'`。注意这里不需要再调用 `getchar`,因为字符已经通过参数传进来了。