计算 C 中的空格和其他数字

标签 c

我正在尝试做 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/

相关文章:

多次调用创建线程的方法

c - 如何在 UBUNTU 中使用 execl 函数删除文件

java - C客户端与Java服务器通信错误

c++ - 为什么 *- 语法/运算符在 C/C++ 中有效?

C自增和变量声明

在 C 中将 float 转换为 IEEE 格式

c - printf() 的行为

c++ - 省略参数名称,C++ vs C

c - 在 Linux 中通过 SIOCGIFCONF 轮询接口(interface)名称

在预处理阶段之后但在汇编阶段之前进行编译