2015-11-25 180 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; 
}