一道c语言题,可以编译,但是不能正常运行
//利用结构体变量输入学生信息并显示
/*大家帮忙看一下啊,出错是在输出student name之后*/
#include <stdio.h>
void output(struct student stu);
struct student
{
long number;
char name[20];
char sex;
float score[3];
};
struct student stu[2];
void main()
{
int i,j;
for(i=0;i<2;i++)
{
printf("请输入第%d个学生的信息\n", i+1);
printf("student number: ");
scanf("%l", &stu[i].number);
printf("student name: ");
//gets(stu[i].name);
scanf("%s", stu[i].name);
printf("student sex(Man or Female): ");
scanf("%c", &stu[i].sex);
printf("student score: ");
for(j=0;j<3;j++)
scanf("%f", &stu[i].score[j]);
}
printf("* * * * * * * * * *输出学生信息* * * * * * * * * *\n");
printf("number name sex score\n");
output(stu[1]);
output(stu[2]);
}
void output(struct student stu)
{
int i;
printf("%-11l", stu.number);
printf("%-9s", stu.name);
printf("%-8c", stu.sex);
for(i=0; i<3; i++)
{
printf("%f ", stu.score[i]);
}
printf("\n");
}
[解决办法]
#include <stdio.h>void output(struct student stu);struct student{ long number; char name[20]; char sex; float score[3];};struct student stu[2];void main(){ int i,j; for(i=0;i<2;i++) { printf("请输入第%d个学生的信息\n", i+1); printf("student number: "); scanf("%ld", &stu[i].number); printf("student name: "); //gets(stu[i].name); scanf("%s", stu[i].name); printf("student sex(Man or Female): "); rewind(stdin); //调整输入缓冲区. scanf("%c", &stu[i].sex); printf("student score: "); for(j=0;j<3;j++) scanf("%f", &stu[i].score[j]); } printf("* * * * * * * * * *输出学生信息* * * * * * * * * *\n"); printf("number name sex score\n"); output(stu[0]); output(stu[1]); //output(stu[2]); //越界了}void output(struct student stu){ int i; printf("%-11l", stu.number); printf("%-9s", stu.name); printf("%-8c", stu.sex); for(i=0; i<3; i++) { printf("%f ", stu.score[i]); } printf("\n");}
[解决办法]
数组元素取越界了,
struct student stu[2];
最大的小标应该为2-1=1.
主函数有取stu[2]。
[解决办法]
#include <stdio.h>struct student{ long number; char name[20]; char sex; float score[3];};struct student stu[2];void output(struct student stu){ int i; printf("%-11l", stu.number); printf("%-9s", stu.name); printf("%-8c", stu.sex); for(i=0; i<3; i++) printf("%f ", stu.score[i]); printf("\n");}int main(){ int i,j; for(i=0;i<2;i++) { printf("请输入第%d个学生的信息\n", i+1); printf("student number: "); scanf("%l", &stu[i].number); printf("student name: "); scanf("%s", stu[i].name); printf("student sex(Man or Female): "); scanf("%c", &stu[i].sex); printf("student score: "); for(j=0;j<3;j++) scanf("%f", &stu[i].score[j]); } printf("* * * * * * * * * *输出学生信息* * * * * * * * * *\n"); printf("number name sex score\n"); output(stu[0]); output(stu[1]);}
[解决办法]
void output(struct student stu);
将之改为void output(struct student *stu);
使用指针传递参数,否则的话, printf("%-9s", stu.name);
这句话执行时出错,建议你看看值传递和指针传递的区别了...