计数器未正确递增

标签 c count integer counter getchar

我的计数器似乎没有增加(对于 C 编程)

int ch;
int counterX = 0;
int counterY = 0;

while(( ch = getchar()) != EOF ) {

    if (ch == 'X'){
        counterX = counterX + 1;
        }
    if (ch == 'Y'){
        counterY = counterY + 1;
        }
}

我做了一些测试,无论我的输入如何,counterX 和 counterY 的数字似乎都没有增加。请帮忙!

最佳答案

只要添加右大括号以及程序的其余部分,应该可以工作。前提是您实际上 X 和/或 Y 出现在输入流上。

例如以下完整程序:

#include <stdio.h>

int main (void) {
    int ch, counterX = 0, counterY = 0;

    while ((ch = getchar()) != EOF) {
        if (ch == 'X')
            counterX = counterX + 1;
        if (ch == 'Y')
            counterY = counterY + 1;
    }
    printf ("X = %d, Y = %d\n", counterX, counterY);
    return 0;
}

当使用 echo XYZZY | 运行时将会testprog,输出:

X = 1, Y = 2
<小时/>

顺便说一句,如果您是一个足够优秀的 C 程序员,可以使用:

while ((a = something) == somethingElse)

构造,您可能也应该了解 counterX++ 简写:-)

关于计数器未正确递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25591033/

相关文章:

javascript - 计算元素在数组中出现的次数

python - 相当于 NumPy 中 Pandas 的 value_counts

Python-在保持前导零的同时将字符串转换为整数

c - 在 C 中使用递归添加到完全二叉树

c - 使用修改后的 ls 执行另一个程序

使用函数和字符数组计算字符串长度的C程序

python - python和C中变量的初始化

sql - 具有多个 COUNT(DISTINCT xxx) 的 PL/SQL SELECT - 意外结果

javascript - 我如何在 JavaScript 中将一个数字分成最多 100 个的 block ?

C# 装箱/包装器 - 自定义类充当整数