題目:有n=3個結構體變量,內含學生學號,姓名和3門課程的成績。要求輸出平均成績最高的學生的信息。
#include <stdio.h>
#define n 3
struct student
{long int number;
char name[20];
float s1,s2,s3;
float average;
};
int main()
{void input(struct student *p);
struct student max(struct student *p);
void print(struct student p);
struct student stu[n],*p=stu;
input(p);
print(max(p));
return 0;
}
void input(struct student *p)
{int i;
for(i=0;i<n;i++)
{printf("enter student%d's number,name,3 scores:",i+1);
scanf("%ld%s%f%f%f",&*(p+i).number,*(p+i).name,&*(p+i).s1,&*(p+i).s2,&*(p+i).s3);
*(p+i).average=(*(p+i).s1+*(p+i).s2+*(p+i).s3)/3.0;
}
}
struct student max(struct student *p)
{int i,max;
max=0;
for(i=1;i<n;i++)
if(*(p+max).average<*(p+i).average) max=i;
return *(p+max);
}
void print(struct student p)
{
printf("number=&ld,name=%s,score1=%f,score2=%f,score3=%f",p.number,p.name,p.s1,p.s2,p.s3);
}
--------------------Configuration: 6 - Win32 Debug--------------------
Compiling...
66.cpp
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(22) : error C2228: left of '.number' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(22) : error C2228: left of '.name' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(22) : error C2228: left of '.s1' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(22) : error C2228: left of '.s2' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(22) : error C2228: left of '.s3' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(23) : error C2228: left of '.average' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(23) : error C2228: left of '.s1' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(23) : error C2228: left of '.s2' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(23) : error C2228: left of '.s3' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(31) : error C2228: left of '.average' must have class/struct/union type
D:\vc 6.0\Microsoft Visual Studio\MyProjects\6\66.cpp(31) : error C2228: left of '.average' must have class/struct/union type
執行 cl.exe 時出錯.
指針訪問成員用->
對象用.
類用::
另外
struct student
嚴格來說,這是C++的寫法,C要用typedef。不過你其實用的是VC++,cpp,其實你寫的是C++