我正在尝试做 The C programming Language 的练习我遇到了一些问题。
#include <stdio.h>
/* count digits, white space, others */
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= ’0’ && c <= ’9’)
++ndigit[c - ’0’];
else if (c == ’ ’ || c == ’\n’ || c == ’\t’)
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n",
nwhite, nother);
}
错误:
E:\Files\C\main.c:3:1: warning: return type defaults to 'int' [-Wreturn-type]
E:\Files\C\main.c:11:9: error: stray '\222' in program
最佳答案
这必须处理 ASCII 值。
例如。如果输入 3
getchar() 返回值 51,它是 3 的 ascii 值
所以我们有 51 的 c,0 的 ASCII 值是 48。 所以 c-'0'=51-48=3 所以你会得到表达式ndigit[3]=ndigit[3]+1,从而增加计数数字3输入的值
关于计算 C 中的空格和其他数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31791866/