我正在爲「科學家和工程師提供C++」課程的代碼。我們已經完成了這本書的一半。我一直在尋找通過論壇,並找到了很多幫助。謝謝大家這個驚人的資源。我想向團隊提出第一個問題進行分析。Array is failed to output one row too early
該項目的目標是
- 通過7column陣列創建60row。
- 它必須能夠爲每個學生取4個等級,給他們一個簡單的平均值和一個加權平均值。
- 輸出等級和平均值。
我把所有東西放在一起,它的近乎完整。當我看到即使只輸入6個學生的成績時,我也有點野心勃勃,輸出60行0。如果有零,我終於可以停止打印成績,但現在它會停止打印一行。
例如,如果我輸入5個學生的成績,則它只輸出到第4個學生,並且輸出第5個。一旦我解決了這個問題,我就完成了。我將添加一個switch語句,允許教師查看HIS想要的初始輸入或運行我的代碼。
#include <iostream>
#include <cmath>
using namespace std;
int grade_Calc(int sg[][5]); //initiates function grade_Calc
const int MAXROWS = 60;
const int MAXCOLS = 5;
int grades [MAXROWS][MAXCOLS];
int i,j;
char answer;
int main()
{
////////ENTER VALUES/GRADES/////
i=1; //ROW LOOP
while (i<MAXROWS)
{
grades [i][0] = i;
cout << "Please enter 4 grades for student: " << grades [i][0] << endl;
// COLUMN LOOP
for (j=1; j<MAXCOLS; j++)
{
cout << "Grade: " << j << " is: ";
cin >> grades [i][j];
}
/////enter another grade?/////
cout << "Would you like to enter another grade? " << endl << endl;
cout << "Enter N for no or Y for yes. " << endl << "Y or NO : ";
cin >> answer;
cout << endl;
if (answer == 'N' || answer == 'n')
break;
else if (answer == 'Y' || answer =='y')
i++;
}
grade_Calc(grades); //passes array grades into function grade_Calc
return 0;
}
int grade_Calc(int sg[][5])
{
int avg_sum = 0; //initializes avg_sum
double grades_weight = 0.0; //initializes grades_weight
double avg_simp = 0.0; //initializes avg_simp
cout << "Stdnt" << "\t" << "Grd1" << "\t" << "Grd2" << "\t" << "Grd3" << "\t" << "Grd4" << "\t" << "Avg1" << "\t" << "Avg2" << endl; //outputs column headings
for (int i = 1; i < MAXROWS; i++) //array rows
{
if (grades [i][j] <= 0)
{
break;
}
else
{
for (int j = 0; j < MAXCOLS; j++) // array columns
{
cout << grades[i][j] << "\t\t"; //outputs array
if (j != 0) //ignores student number
{
avg_sum += grades[i][j]; //adds grades for mean
if ((j == 1) || (j == 4)) //if-else that calculates grades_weight
{
grades_weight += (0.2 * grades [i][j]);
}
else
{
grades_weight += (0.3 * grades [i][j]);
}
}
}
avg_simp = (avg_sum/4.0); //calculates simple_avg (arithmetic mean)
cout << "\t" << avg_simp << "\t" << grades_weight; //outputs simple_avg in Avg1 column and weighted_grade in Avg2 column
avg_sum = 0;
grades_weight = 0.0;
cout << endl;
}
}
return 0;
}
如果你必須儲存5名學生,爲什麼你在1上啓動循環?訪問的元素數是last-first + 1,在你的情況下是4-1 + 1 = 4(最後訪問的元素是索引4,因爲5已經超出循環)。 – cbuchart