[![enter image description here][1]][1]
這是我試過的,但是每當我運行程序時它崩潰並且說錯誤,儘管它編譯正確。它要求我輸入部門編號,但之後並沒有顯示我任何輸出函數和數組來計算gpa
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int STDTs = 25;
const int DEPTs = 7;
void initializeGPAs(double gpa[][DEPTs])
{
for(int i=0;i<STDTs;i++)
for(int j=0;j<DEPTs;j++)
gpa[i][j]=(10+rand()%31)/10;
}
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int i=0;i<STDTs;i++)
{
int sum=0;
for(int j=0;j<DEPTs;j++)
sum+=gpa[j][i];
deptAvg[i]=double(sum/STDTs);
}
}
int StdsOnProbationCount(double gpa[][DEPTs])
{
int ctr=0;
for(int i=0;i<STDTs;i++)
for(int j=0;j<DEPTs;j++)
if(gpa[i][j]<2)
ctr++;
return ctr;
}
int StdsOnProbationCountinDeptX(double gpa[][DEPTs], int x)
{
int ctr=0;
for(int i=0;i<STDTs;i++)
if(gpa[i][x-1]<2)
ctr++;
return ctr;
}
void showReport(double gpa[][DEPTs],string dept_names[], double deptAvg[], int ctr1, int ctr2, int x)
{
cout<<endl;
for(int i=0;i<DEPTs;i++)
{
cout<<'\t'<<dept_names[i]<<" ";
}
cout<<endl;
for(int i=0;i<STDTs;i++)
{
cout<<"Student "<<i+1<<": ";
for(int j=0;j<DEPTs;j++)
cout<<gpa[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(int t=0;t<DEPTs;t++)
cout<<"Dept Avg.: "<<deptAvg[t]<<" ";
cout<<endl<<endl;
cout<<"Total number of students who are on probation is: "<<ctr1;
cout<<endl;
cout<<"Number of students who are on probation in "<<dept_names[x-1]<<" Dept. is "<<ctr2;
}
int main()
{
double gpa[STDTs][DEPTs];
int ctr1, ctr2, x;
double deptAvg[DEPTs];
string dept_names[DEPTs]={"MATH","STAT","COMP","PHYS","CHEM","BIOL","GEOL"};
initializeGPAs(gpa);
computeDeptAvg(gpa, deptAvg);
ctr1 = StdsOnProbationCount(gpa);
cout<<"Enter Department Number [1 to 7]: ";
cin >> x;
ctr2 = StdsOnProbationCountinDeptX(gpa, x);
showReport(gpa, dept_names, deptAvg, ctr1, ctr2, x);
return 0;
}
編輯:我想通了一切,但我的問題似乎是在這個功能,因爲它會顯示所有部門的平均
零void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int i=0;i<STDTs;i++)
{
int sum=0;
for(int j=0;j<DEPTs;j++)
{
sum+=gpa[j][i];
deptAvg[j]=double(sum/STDTs*1.0);
}
}
}
你需要創建一個[MCVE],你也可能會發現[如何調試小程序(https://ericlippert.com/2014/ 03/05/how-to-debug-small-programs /)有用。 –
什麼樣的錯誤?向我們顯示實際的錯誤信息! –
當您訪問您不應該訪問的數據時,您的程序可能會崩潰;在你的情況下在矩陣上使用越界索引;事情like..if(gpa [i] [x-1] <2)似乎對我很可疑 - 你確定x-1是一個有效的索引嗎? – Pandrei