2015-11-25 265 views
0

Codeblocks在我的第一個輸入提示輸入另一個輸入時沒有爲每個輸入提示打印輸出語句時,要求我輸入超出要求的額外輸入。C編程語言

#include <stdio.h> 
//Computing marks and average of students using 2D arrays 
void main() 
{ 
    int i,j,sum,marks[3][5]; 
    float avg; 
    printf("Program to compute average marks of 3 students.\n"); 
    for(i=0;i<3;i++) 
    { for(j=0;j<5;j++) 
    { 
     printf("Enter marks for student %d in subject %d:\t",i+1,j+1); 
     scanf("%d ",&marks[i][j]); 
    } 
    } 
    for(i=0;i<3;i++) 
    { 
     for(j=0;j<5;j++) 
     { 
      sum=sum+marks[i][j]; 
     } 
     avg= sum/5.0; 
     printf("The average marks of student %d is %f:\n",i+1,avg); 
     } 
    getch(); 
} 
+2

'void main'最有可能是**錯誤**。 – Downvoter

+0

請更改標題並刪除代碼塊代碼:此問題與CodeBlocks無關。 –

回答

2

問題代碼: 您的格式字符串像scanf("%d ",&marks[i][j]);需要輸入空格之後導致異常。

更正代碼:

#include <stdio.h> 
//Computing marks and average of students using 2D arrays 
int main() 
{ 
    int i,j,sum = 0,marks[3][5]; 
    float avg; 

    printf("Program to compute average marks of 3 students.\n"); 
    for(i=0;i<3;i++) 
    { 
     for(j=0;j<5;j++) 
     { 
      printf("Enter marks for student %d in subject %d:\t",i+1,j+1); 
      scanf("%d",&marks[i][j]); 
     } 
    } 
    for(i=0;i<3;i++) 
    { 
     for(j=0;j<5;j++) 
     { 
      sum=sum+marks[i][j]; 
     } 
     avg= sum/5.0; 
     printf("The average marks of student %d is %f:\n",i+1,avg); 
    } 
    return 0; 
} 

爲規範說

數量,順序和轉換規範的類型必須在列表

的參數 數量,順序和類型相匹配

。否則,結果將不可預知,並可能終止輸入/輸出功能。

0

正如評論所說,void main()是不好的:你應該使用int main()return 0;

結束你的程序,但問題是簡單地通過一個不必要的空間,在你輸入的格式在"%d "引起的。這將刪除問題:

scanf("%d",&marks[i][j]); 
2

scanf函數格式字符串應該是"%d"(沒有空格)。您也忘記初始化總和變量。以下是您的代碼的更正版本,其中包含一個方便的數組長度宏。希望這可以幫助。

#include <stdio.h> 
#include <stdlib.h> 

#define LEN(arr) (sizeof (arr)/sizeof (arr)[0]) 

/*Computing marks and average of students using 2D arrays*/ 

int main() 
{ 
    int i, j, sum, marks[3][5], count; 
    float avg; 

    printf("Program to compute average marks of 3 students.\n"); 
    for (i = 0; i < LEN(marks); i++) { 
     for (j = 0; j < LEN(marks[0]); j++) { 
      printf("Enter marks for student %d in subject %d:\t", i + 1, j + 1); 
      count = scanf("%d", &marks[i][j]); 
      if (count != 1) { 
       fprintf(stderr, "invalid input\n"); 
       exit(EXIT_FAILURE); 
      } 
     } 
    } 
    for (i = 0; i < LEN(marks); i++) { 
     sum = 0; 
     for (j = 0; j < LEN(marks[0]); j++) { 
      sum = sum + marks[i][j]; 
     } 
     avg = ((float) sum)/((float) LEN(marks[0])); 
     printf("The average marks of student %d is %f:\n", i + 1, avg); 
    } 

    return 0; 
}