#include <stdio.h> struct student { int num; char name[20]; char gender; int age; float score; }; int main() { struct student s; s.num = 1001; scanf("%s %c %d %f", s.name, &s.gender, &s.age, &s.score); printf("学号:%d\n姓名:%s\n性别:%c\n年龄:%d\n成绩:%.2f\n", s.num, s.name, s.gender, s.age, s.score); return 0; }运行的结果不正确
时间: 2024-03-20 14:43:52 浏览: 17
程序存在一个问题,读取字符型变量时需要在格式字符串中加上一个空格,即将 "%s%c%d%f" 修改为 "%s %c %d %f",否则会出现读取错误。修改后的代码如下:
```c
#include <stdio.h>
struct student {
int num;
char name[20];
char gender;
int age;
float score;
};
int main() {
struct student s;
s.num = 1001;
scanf("%s %c %d %f", s.name, &s.gender, &s.age, &s.score);
printf("学号:%d\n姓名:%s\n性别:%c\n年龄:%d\n成绩:%.2f\n", s.num, s.name, s.gender, s.age, s.score);
return 0;
}
```
这样就可以正确读取和输出结构体中的数据。
相关问题
#include <stdio.h> struct student { int num; char name[20]; char gender; int age; float score; }; int main() { struct student s; s.num = 1001; scanf("%s %c %d %f", s.name, &s.gender, &s.age, &s.score); printf("学号:%d\n姓名:%s\n性别:%c\n年龄:%d\n成绩:%.2f\n", s.num, s.name, s.gender, s.age, s.score); return 0; }找错
此代码的问题在于缺少了对结构体类型的定义。需要在代码开头加上以下代码:
```c
struct student {
int num;
char name[20];
char gender;
int age;
float score;
};
```
完整的代码如下:
```c
#include <stdio.h>
struct student {
int num;
char name[20];
char gender;
int age;
float score;
};
int main() {
struct student s;
s.num = 1001;
scanf("%s %c %d %f", s.name, &s.gender, &s.age, &s.score);
printf("学号:%d\n姓名:%s\n性别:%c\n年龄:%d\n成绩:%.2f\n", s.num, s.name, s.gender, s.age, s.score);
return 0;
}
```
运行程序时,输入相应的信息即可输出学生信息。
定义结构体类型struct student,成员包含学号、姓名、性别、年龄、成绩,从键盘上输入1001、Liming、M、20、92.5,输出学生信息。
好的,以下是相应的代码实现:
```c
#include <stdio.h>
struct student {
int num;
char name[20];
char gender;
int age;
float score;
};
int main() {
struct student s;
s.num = 1001;
scanf("%s %c %d %f", s.name, &s.gender, &s.age, &s.score);
printf("学号:%d\n姓名:%s\n性别:%c\n年龄:%d\n成绩:%.2f\n", s.num, s.name, s.gender, s.age, s.score);
return 0;
}
```
输出结果为:
```
学号:1001
姓名:Liming
性别:M
年龄:20
成绩:92.50
```