【问题标题】:Counter is not incrementing properly计数器未正确递增
【发布时间】:2014-08-31 10:22:49
【问题描述】:

我的计数器似乎没有增加(对于 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 的数量似乎并没有增加,无论我的输入如何。请帮忙!

【问题讨论】:

  • 您提交的代码不可编译,因为您错过了 ch 的定义并且您错过了包含 while 循环的大括号 - 该大括号可能至关重要。
  • sry 这只是我当前程序中存在问题的粗略部分。不好编辑它

标签: c count integer counter getchar


【解决方案1】:

如果您添加右大括号和程序的其余部分,那 应该 可以工作。并且假设您实际上 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++ 的简写:-)

【讨论】:

  • 是的,我的错,我忘了把我的输出放在我的循环中。还是谢谢
猜你喜欢
  • 2016-02-03
  • 2022-01-25
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 2017-05-18
  • 2021-06-23
  • 2014-10-02
  • 1970-01-01
相关资源
最近更新 更多