我正在嘗試制作一個 GPA 平均計算器,用戶可以在其中輸入最多 30 個 GPA 分數。如果 < 30,用戶可以選擇繼續添加 GPA 分數,或者使用給定的分數計算當前的 GPA 平均值。我試圖讓我的代碼作業,以便它跳過陣列中包含值 0(由用戶輸入)的元素,這樣它們就不會包含在總和中。我嘗試了不同的 if 陳述句以跳過包含 0 但都失敗的值。
輸入:
10、2、38 輸出:16.00(GPA 平均值)
輸入:10, 2, 0, 38
輸出:12.00(GPA 平均值)
期望輸出:16.00 <-- 我想跳過用戶輸入的任何“0”值。
#include <stdio.h>
int main() {
int option = 0;
int iArray[30] = { 0 };
int choice;
int counter = 0;
int sum = 0;
float average;
do {
printf("\nEnter GPA score here: ");
scanf(" %d", &iArray[counter]);
counter ;
printf("\n1\tEnter a new GPA? Please enter \"1\".");
printf("\n2\tCalculate the current GPA average? Please enter \"2\".\n");
printf("\n\nPlease enter choice here: ");
scanf(" %d", &choice);
} while (choice == 1 && counter < 30);
if (choice == 2) {
for (int x = 0; x < counter; x ) {
if (iArray[x] >= 1) { //skip over elements with value of 0
sum = iArray[x];
}
}
}
average = sum / counter;
printf("\n\nThe average GPA is %.2f ", average);
return 0;
}
uj5u.com熱心網友回復:
您添加的 GPA 并沒有小于1您的sum,但是您的平均值只是除以counter您計算所有成績輸入的變數。
如果您引入一個新的計數器變數來跟蹤有多少個零 GPA,您可以從成績輸入的總計數中減去它。
請注意,如果您將int總和除以int計數器int,即使您將該值分配給float變數,您也會得到。為避免這種情況,請強制使用sumtofloat以便進行浮點數學運算。
uj5u.com熱心網友回復:
這是一個邏輯問題。即使sum在值大于 0 時完成counter,輸入的總數也是如此。
您可以維護另一個計數器,例如counter_filtered,僅在滿足if條件時才增加它。
int counter_filtered = 0 //--> New variable
if (choice == 2) {
for (int x = 0; x < counter; x ) {
if (iArray[x] >= 1) { //skip over elements with value of 0
sum = iArray[x];
counter_filtered ; //--> New variable increment
}
}
}
average = sum / counter_filtered; //--> New variable usage in calculations
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321561.html
