【发布时间】:2019-02-17 18:56:00
【问题描述】:
今天是我第一次使用 C,我尝试了一些东西,比如 if、getchar() 等。但现在我的问题是,我的代码中的第三个 printf() 打印了它不应该打印的东西。但我不知道问题出在哪里。
循环应该采用 c 整数,并且应该在每个“循环”中添加“1”。但是当我输入“5”时,循环打印:
You entered: 54
You entered: 55
You entered: 56
You entered: 57
You entered: 58
You entered: 59
You entered: 60
You entered: 61
You entered: 62
You entered: 63
You entered: 64
You entered: 65
You entered: 66
You entered: 67
但它应该打印如下内容:
You entered: 6
You entered: 7
You entered: 8
You entered: 9
You entered: 10
You entered: 11
You entered: 12
You entered: 13
You entered: 14
You entered: 15
You entered: 16
You entered: 17
You entered: 18
You entered: 19
我的代码
#include <stdio.h>
int main()
{
printf("Enter a value!: ");
int c = getchar();
printf("You entered: %c\n", c);
int x = 1;
while(x < 15) {
x++;
c++;
printf("You entered: %d\n", c);
}
return 0;
}
【问题讨论】:
-
getchar() 获取字符而不是整数。 5 的 ascii 是 53,这就是它从 54 开始的原因。
-
使用
scanf()而不是getchar()来获取数字。
标签: c