我正在尝试编写一个存储数组的简单程序,然后返回它。但是,它没有正确返回所有数字,特别是在数组的末尾。以下是输出的示例:
Please enter number of numbers
5
Please enter number 1
2
Please enter number 2
3
Please enter number 3
5
Please enter number 4
6
Please enter number 5
7
Number 1 is 2
Number 2 is 3
Number 3 is 5
Number 4 is 14
Number 5 is 1
logout
[Process completed]
and here is my code:
#include <stdio.h>
int main (void) {
int i, num;
int x[num];
printf("Please enter number of numbers\n");
scanf("%d",&num);
for (i = 0; i < num; i++) {
printf("Please enter number %d\n", i + 1);
scanf("%d",&x[i]);
}
for (i = 0; i < num; i++) {
printf("Number %d is %d\n", i + 1, x[i]);
}
return 0;
}
答案 0 :(得分:2)
在扫描num之前,您正在执行int x[num]
,而num
存储垃圾值,您无法获得正确的输出。
int main (void) {
int i, num;
// int x[num]; // num is not defined here
printf("Please enter number of numbers\n");
scanf("%d",&num);
int x[num];
for (i = 0; i < num; i++) {
printf("Please enter number %d\n", i + 1);
scanf("%d",&x[i]);
}
for (i = 0; i < num; i++) {
printf("Number %d is %d\n", i + 1, x[i]);
}
return 0;
}
答案 1 :(得分:2)
我认为你应该初始化num变量,这样它最初就不会有垃圾值..