[英]Elements in my array are storing incorrect values even after user is being prompted
I'm trying to create a score storing program where I ask a user for scores to store in an array and just print them out at the end of it.我正在尝试创建一个分数存储程序,在该程序中我要求用户将分数存储在一个数组中,然后在最后打印出来。 However, when I tried to do that, the values of the array are being changed to 32764, 4198754 etc.
但是,当我尝试这样做时,数组的值正在更改为 32764、4198754 等。
My code:我的代码:
int main (void){
int score;
//int sum = 0;
int num_score = get_int("Enter the number of scores: ");
int scores[num_score];
printf("Enter Scores below\n");
for (int i = 1; i <= num_score; i++){
score = get_int("Score %i: " ,i);
score = scores[i];
}
printf("The scores are as follows: \n");
for (int i = 1; i <= num_score; i++ ){
//sum = sum + scores[i];
printf("Score %i = %i\n",i,scores[i]);
}
For example, if there are a total of 3 scores, and the user enters score 1 = 78, score 2 = 67 and score 3 = 83 The expected output should be:例如,如果总共有 3 个分数,用户输入 score 1 = 78, score 2 = 67, score 3 = 83 预期的 output 应该是:
Score 1 = 78
Score 2 = 67
Score 3 = 83
Instead, the values that were printed out are as follows:相反,打印出来的值如下:
Score 1 = 32767
Score 2 = 4198754
Score 3 = 0
Why is this so?为什么会这样? I'd like to understand see where I went wrong.
我想了解一下我哪里出错了。
You misused the assignment operator here:您在这里误用了赋值运算符:
score = scores[i];
The assignment operator sets the value of lefthand operand to the value of righthand operand .赋值运算符将左侧操作数的值设置为右侧操作数的值。
It should be:它应该是:
scores[i] = score;
Also the array declaration还有数组声明
int scores[num_score];
should be应该
int scores[num_score+1];
To enable usage of scores[num_score]
.启用
scores[num_score]
的使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.