c语言程序设计定义学生结构体初始化5名学生的学号、姓名及成绩。struct stu s5=201Zhang78202Li85203Wang60204Wang75205Xue80;编写程序根据用户输入的n值输出升序或降序排列的学生信息。输入1输出降序排列的学生信息;输入2输出升序排列的学生信息。输出格式:-8d-8sdn
#include <stdio.h> #include <string.h>
struct stu{ int num; char name[20]; int score; };
int main() { struct stu s[5]={{201,"Zhang",78},{202,"Li",85},{203,"Wang",60},{204,"Wang",75},{205,"Xue",80}}; int n, i, j; struct stu temp;
printf("Please enter 1 for descending order or 2 for ascending order: ");
scanf("%d", &n);
if(n==1){
//descending order
for(i=0;i<4;i++){
for(j=i+1;j<5;j++){
if(s[i].score<s[j].score){
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
printf("Student information in descending order:\n");
printf("%-8s%-8s%s\n", "Number", "Name", "Score");
for(i=0;i<5;i++){
printf("%-8d%-8s%d\n", s[i].num, s[i].name, s[i].score);
}
}
else if(n==2){
//ascending order
for(i=0;i<4;i++){
for(j=i+1;j<5;j++){
if(s[i].score>s[j].score){
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
printf("Student information in ascending order:\n");
printf("%-8s%-8s%s\n", "Number", "Name", "Score");
for(i=0;i<5;i++){
printf("%-8d%-8s%d\n", s[i].num, s[i].name, s[i].score);
}
}
else{
printf("Invalid input.");
}
return 0;
原文地址: http://www.cveoy.top/t/topic/f4k0 著作权归作者所有。请勿转载和采集!