几十年前我做过一些 C 编程。我正在尝试重新学习语言。我写了这个。我得到了一些意想不到的东西。当我将“short int”更改为“int”时,它似乎有效。任何人都可以查看我的代码以查看它是否有任何问题或者这是编译器问题。我在 Linux 上使用 gcc。
#include <stdio.h>
int main(void) {
short int age = 0;
short int num_1_yr_olds = 0;
short int num_2_and_3_yr_olds = 0;
short int num_above_3_yr_olds = 0;
while(1) {
printf ("Enter age: ");
scanf ("%d", &age);
if (age < 1) {
break;
}
switch (age) {
case 1:
++num_1_yr_olds;
break;
case 2:
case 3:
++num_2_and_3_yr_olds;
break;
default:
++num_above_3_yr_olds;
break;
}
}
printf ("Number of 1 year olds = %d\n", num_1_yr_olds);
printf ("Number of 2 and 3 year olds = %d\n", num_2_and_3_yr_olds);
printf ("Number above 3 year olds = %d\n", num_above_3_yr_olds);
}
输入
Enter age: 1
Enter age: 1
Enter age: 1
Enter age: -1
输出
Number of 1 year olds = -1
Number of 2 and 3 year olds = 0
Number above 3 year olds = 0
num_1_yr_olds 值被搞砸了。我期望一个 3,我得到一个 -1。无论输入如何,num_1_yr_olds 的值都会变为 -1。