2012-10-09 47 views
0

我被困在一個問題上。我正在嘗試在此計劃任務中找到QUIZZES的平均值。這是我的代碼。 Bold中的代碼是我的問題所在。c編程測驗平均數組for循環

#include <stdlib.h> 
#include <stdio.h> 
#define STUDENTS 4 
#define QUIZZES 5 

main() { 

int quizScores [STUDENTS] [QUIZZES] = { 
    { 90, 90, 90, 90, 90 }, 
    { 90, 80, 70, 60, 50 }, 
    { 90, 89, 88, 87, 86 }, 
    { 90, 85, 80, 75, 70 } 
}; 
int studentTotal = 0, quizTotal, row, col; 
double studentAverage, quizAverage; 

for (row = 0; row < STUDENTS; row++) { 
    studentTotal = 0; 
    for (col = 0; col < QUIZZES; col++) { 
     studentTotal += quizScores[row][col]; 
    } 
    studentAverage = (double) studentTotal/QUIZZES; 
    printf("Student %i has average %.2lf\n", row, studentAverage); 
} 

**for (col = 0; col < QUIZZES; col++) { 
    quizTotal = 0; 
    for (row = 0; row < STUDENTS; row++) { 
     quizTotal += quizScores[col][row]; 
    } 
    quizAverage = (double) quizTotal/STUDENTS; 
    printf("Quiz %i has an average %.2lf\n",col, quizAverage); 
    // output the average for this quiz 
}** 

system("pause"); 
} 
+0

請注意,調試諸如此類問題的有效方法是在您處理它們時打印正在處理的值。您也可以使用調試器來查看代碼,看看發生了什麼。例如,如果你在第二個循環中打印了'printf(「測驗[%d] [%d] =%f \ n」,col,row,quizScores [col] [row]);''數字隨你走,這會讓你看起來很難看代碼。 –

回答

1

您的指數混合在quizTotal += quizScores[col][row];。它應該是quizTotal += quizScores[row][col];

+0

><簡單的錯誤。謝謝你指出。我想知道爲什麼我的「測驗4有平均值」的輸出一直給我一個負面的奇怪數字,例如-3215461312513.15。謝謝。 –