我有以下代码:
#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/