我一直在编写一个代码,用来存储学生的名字和成绩,然后在输入学生的名字时回想起成绩。
下面是我的代码:
#include <stdio.h>
#define N 10
#define M 2
struct a
{
char name[50];
int grade;
};
int main()
{
int i;
int j;
struct a A[N][M];
for(i=0;i<N;i++)
{
printf("Please Enter Students' Names:/n");
scanf("%s", &A[i].name);
}
for(j=0;j<M;j++)
{
printf("Please Enter Students' Grades:/n");
scanf("%d", &A[j].grade);
}
printf("Which Student's Grades Would You Like To View?/n");
if(scanf("%s", *A[i].name))
{
printf("Their Grade Is:%d/n", *A[j].grade);
}
return 0;
}
我一直收到以下错误:
hw2problem2.c(21): error: expression must have struct or union type
scanf("%s", &A[i].name);
^
hw2problem2.c(26): error: expression must have struct or union type
scanf("%d", &A[j].grade);
^
hw2problem2.c(29): error: expression must have struct or union type
if(scanf("%s", *A[i].name))
^
hw2problem2.c(31): error: expression must have struct or union type
printf("Their Grade Is:%d/n", *A[j].grade);
^
compilation aborted for hw2problem2.c (code 2)
对错误或程序的任何帮助都将不胜感激。谢谢。
发布于 2014-10-09 12:02:49
您将struct a A
定义为二维数组,并且只在scanf("%s", &A[i].name);
和scanf("%d", &A[j].grade);
中指定了一维。
你还有一些其他的问题,比如scanf("%s", &A[i].name);
..。其中&
是不必要的。
发布于 2014-10-09 11:51:38
你的程序应该是这样的
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
printf("Please Enter Students' Grades:/n");
scanf("%d", &A[i][j].grade);
printf("Please Enter Students' Names:/n");
scanf("%s", &A[i][j].name);
}
}
因为,A[i]
的类型是struct a*
,而不是struct a
。应该是Ai
从逻辑上讲,你的数组应该是一维的。因此,循环应该如下所示:
struct a A[N];
for(i=0;i<N;i++)
{
printf("Please Enter Students' Names:/n");
scanf("%s", &A[i].name);
}
for(j=0;j<N;j++)
{
printf("Please Enter Students' Grades:/n");
scanf("%d", &A[j].grade);
}
如果它是主题,那么它应该是2D的,并使用嵌套循环,如图所示。
发布于 2014-10-09 12:55:18
不需要使用2D
数组。简单地试一下这个..
#include <stdio.h>
#define N 3
struct a
{
char name[50];
int grade;
};
int main()
{
int i;
struct a A[N];
char sname[50];
for(i=0;i<N;i++)
{
printf("Please Enter Students' Names:/n");
scanf("%s", A[i].name);
}
for(i=0;i<N;i++)
{
printf("Please Enter Students' Grades:/n");
scanf("%d",&A[i].grade);
}
printf("Which Student's Grades Would You Like To View?/n\n");
printf("Enter the name...\n");
scanf("%s",sname);
for(i=0;i<N;i++)
{
if(strcmp(A[i].name,sname)==0)
{
printf("%s grade is %d\n",A[i].name,A[i].grade);
break;
}
else
{
if(i==N-1)
printf("No such a name in your list...\n");
}
}
return 0;
}
https://stackoverflow.com/questions/26269993
复制相似问题