2014-01-10 40 views
0

/*在下面的程序中,我想接受5個主題中任意數量學生的標記,將它們存儲在名爲「標記」的數組中,然後計算平均分數f每個學生超過5個科目。然而,它似乎只接受你輸入的最後一名學生的分數。c中的多維數組不會接受我的輸入

我想知道程序中的錯誤?


{ 
    char subject[5][10]= 
    { 
     "Maths", 
     "Physics", 
     "English", 
     "Chemistry", 
     "Biology", 
    }; 


    char student[30][20],ans; 
    int marks [30][5],i,j,nos, total; 
    float studavg[30], subavg[5]; 
    main() 
    { 
     for (ans='y',i=0;i<30 && ans=='y';i++) 
     { 
      printf("\nEnter student number: %d",i+1); 
      gets(student[i]); 
      fflush(stdin); 
      printf("more? (y/n)"); 
      ans=getchar(); 
      fflush(stdin);  
     } 
     nos=i; 
/*that part initializes my student array and saves the no of students*/ 

     for (i=0;i<nos;i++) 
     { 
      for (j=0;j<5;j++) 
      { 
       marks[i][j]=0; 
       printf("Enter the marks for %s in %s",student[i],subject[j]); 
       scanf("%d",&marks[i][j]); 
       fflush(stdin);  
      }     
     }  
    /*this part is supposed to create an array of student marks*/ 


     for (i=0;i<nos;i++) 
     { 
      for (j=0;j<5;j++) 
      { 
       total+=marks[i][j];   
      } 
      studavg[i]=total/5; 
     } 
    } 

/*the last part was to find the student average*/} 
+3

切勿使用'gets';它本質上是不安全的,並已從語言中刪除。改用'fgets';使用起來有點複雜,但是可以限制它接受的輸入大小。不要使用'fflush(stdin)';它有未定義的行爲。 –

回答

1

您必須清除total爲每個新學生:

for (i = 0; i < nos; i++) 
{ 
    for (j = total = 0; j < 5; j++) 
    { 
     total += marks[i][j]; 
    } 
    studavg[i] = total/5; 
} 
+0

此外total還沒有初始化 – zoska

+0

@zoska沒錯,但我的解決方法也解決了這個問題。 :) – unwind

+0

是的,開始評論你的編輯之前。 – zoska