繁体   English   中英

即使在提示用户之后,我的数组中的元素也存储了不正确的值

[英]Elements in my array are storing incorrect values even after user is being prompted

我正在尝试创建一个分数存储程序,在该程序中我要求用户将分数存储在一个数组中,然后在最后打印出来。 但是,当我尝试这样做时,数组的值正在更改为 32764、4198754 等。

我的代码:

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]);
        }
 

例如,如果总共有 3 个分数,用户输入 score 1 = 78, score 2 = 67, score 3 = 83 预期的 output 应该是:

Score 1 = 78
Score 2 = 67
Score 3 = 83

相反,打印出来的值如下:

Score 1 = 32767
Score 2 = 4198754
Score 3 = 0

为什么会这样? 我想了解一下我哪里出错了。

您在这里误用了赋值运算符:

score = scores[i]; 

赋值运算符将左侧操作数的值设置为右侧操作数的值。

它应该是:

scores[i] = score;

还有数组声明

int scores[num_score];

应该

int scores[num_score+1];

启用scores[num_score]的使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM