c - 不正确的变量值递增

标签 c

我有以下代码:

#include <stdio.h>
#include <ctype.h>

int main(int argc, char **argv)
{
        int ch, lower, upper = 0;
        printf("Enter a line of text: \n");
        while ((ch = getchar()) != EOF) {
        if (islower(ch)) {
                ch = toupper(ch);
                ++upper;
        } else if (isupper(ch)) {
                ch = tolower(ch);

                printf("Looking at lower: %d\n", lower);
                ++lower;
                printf("Looking at lower: %d\n", lower);
        }
        putchar(ch);
        }
        printf("Hello\n");
        printf("\nRead %d characters in total. %d converted to upper-case, %d to lower-case.", upper+lower, upper, lower);
}

出于某种原因,upper 变量设置正确,但无法弄清楚 lower 给出错误值的原因。例如。如果我输入“Football”,它会显示 4195825 转换为小写,实际输出应为 1。

我看不出哪里错了。

最佳答案

你还没有初始化 lower。它的值(value)是不确定的。

C11:6.7.9 初始化(p10):

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

将其初始化为0

int ch, lower = 0, upper = 0;  

关于c - 不正确的变量值递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22923235/

相关文章:

c - 为 C printf 设置千位分隔符

c - 在哪里可以找到奇怪的、特定的 C 语法规则?

c - 我正在编写一个程序来更改文件位置。但它无法正常工作

c - `getchar()` 给出与输入字符串相同的输出

c - 缓冲区溢出示例适用于 Windows,但不适用于 Linux

c - strlen 对字符串指针的计算不正确?

不能在幂函数中使用常数

c - 没有优化的 gcc 段错误

c - linux 编程,标准输出到管道在 execve 之前不起作用

c - C程序中单独线程的优点