![](/img/trans.png)
[英]my array storing the values only until iterations runs..after completing the storing of values and trying to get those values it returns Null values
[英]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.