![]() |
#2
纯蓝之刃2020-06-15 14:28
![]() #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> struct student { int num; char name[20]; int sex; float score; }; int main() { struct student* stu; int n, i, j = 0, first = 0,dot=0; int m; char str[256]; float score[2]; int num[2]; memset(score, 0, sizeof(float) * 2); memset(num, 0, sizeof(int) * 2); printf("请输入学生个数:"); scanf("%d", &n); getchar(); stu = (struct student*)malloc(sizeof(struct student) * n); for(j=0;j<n;j++) { memset(str,0,256); fgets(str,256,stdin); first = 0; i = 0; while (str[i] != ';') { if (first == 0) { (stu + j)->num = str[i] - '0'; first = 1; } else (stu + j)->num = (stu + j)->num * 10 + str[i]-'0'; i++; } m = i+1; while (str[++i] != ';'); memset((stu + j)->name, 0, 20); memcpy((stu + j)->name, &str[m],i-m); first = 0; while (str[++i] != ';') { if (first == 0) { (stu + j)->sex = str[i] - '0'; first = 1; } else (stu + j)->sex = (stu + j)->sex * 10 + str[i] - '0'; } first = 0; dot = 0; while (str[++i] != ';') { if (first == 0) { (stu + j)->score = (float)(str[i] - '0'); first = 1; } else { if (str[i] == '.') { dot = 1; } else { if (dot) { (stu + j)->score = (stu + j)->score+ (str[i] - '0')/(float)pow(10,dot++); } else { (stu + j)->score = (stu + j)->score * 10 + str[i] - '0'; } } } } printf("%d,%s,%d,%f\n", (stu + j)->num, (stu + j)->name, (stu + j)->sex, (stu + j)->score); } for (j = 0; j < n; j++) { if ((stu + j)->sex == 0) { score[0] += (stu + j)->score; num[0]++; } else { score[1] += (stu + j)->score; num[1]++; } } printf("女 %.2f\n", score[0] / num[0]); printf("男 %.2f\n", score[1] / num[1]); return 0; } |
编写一个C语言程序,输入n,然后输入n个学生信息,分别统计并输出男、女(sex=0女、 sex=1男)同学的平均成
绩.
要求:使用动态内存分配,输出整数值,若某性别学生没有则不输出,已知学生信息定义如下:
struct student
int num;
char name[20];
int sex;
float score;
(注意]输入n和每位字生的信息各占一行,输入的字生各项信思间用半角空格分隔;输出先女后男,每个性别占
-行 (若某各性别没有输入则不输出),,性别 和平均成绩之间用一一个半角空格分隔,输入输出格式如下所示(下例
内容前5行为输入,后两行为输出),格式错误算结果错误。
1张三166
2李四178
3小红065
4王五165
女65
男69