C++ 学生成绩排序程序代码优化
本文提供一段 C++ 代码用于排序学生成绩,并对代码进行了优化,使其更易读、更规范。
原始代码:
#include<iostream>
#include<string.h>
using namespace std;
struct student {
int stnumber;
string name;
float scores;
}st[100];
void Sort(int n,student* st) {
int i,j;
student temp;
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++) {
if(st[j].scores >st[j+1].scores)
temp=st[j];
st[j]=st[j+1];
st[j+1]=temp;
}
}
void Set(int n,student* st) {
int i;
cout<<'依次输入学生信息:(学号,姓名,成绩)'<<endl;
for(i=0;i<n;i++)
cin>>st[i].stnumber>>st[i].name>>st[i].scores ;
}
void Show(int n,student* st) {
int i;
cout<<'排序结果如下:'<<endl;
for(i=0;i<n;i++)
cout<<'学号:'<<st[i].stnumber<<' 姓名:'<<st[i].name <<' 成绩:'<<st[i].scores<<endl;
}
int main() {
int n;
cout<<'输入学生个数:';
cin>>n;
Set(n,st);
Sort(n,st);
Show(n,st);
return 0;
}
代码优化:
- 头文件和命名空间的格式不正确,应该写成:
#include <iostream>
#include <string>
using namespace std;
- 结构体的定义中,变量名应该放在类型名的后面,应该写成:
struct student {
int stnumber;
string name;
float scores;
};
- 排序函数中,if语句只对第一条语句进行了判断,应该加上花括号把两条语句包起来:
if(st[j].scores > st[j+1].scores) {
temp = st[j];
st[j] = st[j+1];
st[j+1] = temp;
}
- 在主函数中,应该先定义结构体数组再传入函数中,应该写成:
int main() {
int n;
cout << '输入学生个数:';
cin >> n;
student st[100];
Set(n, st);
Sort(n, st);
Show(n, st);
return 0;
}
- 在输入学生信息时,应该加上提示信息,应该写成:
cout << '依次输入学生信息:(学号,姓名,成绩)' << endl;
for (i = 0; i < n; i++) {
cout << '第' << i+1 << '个学生:';
cin >> st[i].stnumber >> st[i].name >> st[i].scores;
}
- 在输出排序结果时,应该加上序号,应该写成:
cout << '排序结果如下:' << endl;
for (i = 0; i < n; i++) {
cout << '第' << i+1 << '名:';
cout << '学号:' << st[i].stnumber << ' 姓名:' << st[i].name << ' 成绩:' << st[i].scores << endl;
}
优化后的代码:
#include <iostream>
#include <string>
using namespace std;
struct student {
int stnumber;
string name;
float scores;
};
void Sort(int n, student* st) {
int i, j;
student temp;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++) {
if (st[j].scores > st[j + 1].scores) {
temp = st[j];
st[j] = st[j + 1];
st[j + 1] = temp;
}
}
}
void Set(int n, student* st) {
int i;
cout << '依次输入学生信息:(学号,姓名,成绩)' << endl;
for (i = 0; i < n; i++) {
cout << '第' << i + 1 << '个学生:';
cin >> st[i].stnumber >> st[i].name >> st[i].scores;
}
}
void Show(int n, student* st) {
int i;
cout << '排序结果如下:' << endl;
for (i = 0; i < n; i++) {
cout << '第' << i + 1 << '名:';
cout << '学号:' << st[i].stnumber << ' 姓名:' << st[i].name << ' 成绩:' << st[i].scores << endl;
}
}
int main() {
int n;
cout << '输入学生个数:';
cin >> n;
student st[100];
Set(n, st);
Sort(n, st);
Show(n, st);
return 0;
}
通过以上优化,代码结构更加清晰,代码可读性更强。同时,也避免了潜在的错误,提高了代码的可靠性。', 'url': nul
原文地址: https://www.cveoy.top/t/topic/jDxx 著作权归作者所有。请勿转载和采集!