2016年北理复试上机
1、输入学生姓名和成绩(数目不定),输出每个学生的姓名和平均成绩。另外,不及格课程数超过2的学生,按不及格课程数从大到小排序输出。
#include<iostream> #include<string> #include<algorithm> using namespace std; struct Student { int id; string name; int score[100]; int fnum;//不及格成绩数量 double avg; }t[100]; bool cmp(Student a, Student b) { return a.fnum < b.fnum; } int main() { cout << "输入学生姓名和成绩(每行一个学生)" << endl; string s[105]; int n = 0;//行数 while (getline(cin, s[n++])); n--;//移除Ctrl+Z的一行 for (int i = 0; i < n; i++) { int j = 0; while (s[i][j] != ' '&&s[i][j] != '\0')t[i].name += s[i][j++];//提取姓名 int cnt = 0;//记录成绩的数量 while (s[i][j] != '\0')//录入成绩 { int tmp = 0;//这时候的j在空格位 while (s[i][++j] != ' '&&s[i][j] != '\0')tmp = tmp * 10 + s[i][j] - '0'; t[i].score[cnt++] = tmp; } double total = 0; int fn = 0; for (int k = 0; k < cnt; k++)//计算平均成绩和不及格成绩数 { total += (double)t[i].score[k]; if (t[i].score[k] < 60)fn++; } double av = total / ((double)cnt); t[i].avg = av; t[i].fnum = fn; } for (int i = 0; i < n; i++) { cout << t[i].name << " " << t[i].avg << endl; } sort(t, t + n, cmp); for (int i = 0; i < n; i++) { if (t[i].fnum > 2)cout << t[i].name << "的不及格科目数目为" << t[i].fnum << endl; } return 0; }
2、输入字符串,输出字符串中包含的数字,比如 2.3ABC0-2.3 输出 2.3 0 -2.3。注意一些特殊的情况如+004.500值为+4.5。针对示例码了一下,有其他情况请指正。
#include<iostream> #include<string> using namespace std; int main() { string s; cin >> s; string o = "";//输出数字串 int n = 0;//o的长度 bool first = true; for (int i = 0; i < s.size(); i++) { if (s[i] == '+' || s[i] == '-')//正负号下一位必须是数字才可以 { if (i != s.size() - 1) { if (s[i + 1] >= '0'&&s[i + 1] <= '9') { o += s[i]; n++; } } } else if ((s[i] >= '1'&&s[i] <= '9')||(s[i]=='0'&&s[i+1]=='.')) { bool dot = false;//一串数字只能有一个小数点 o += s[i]; n++; i++; while ((i<s.size())&&((s[i] >= '0'&&s[i] <= '9') || (s[i] == '.' && (!dot))))//读完整个数字串 { if (s[i] >= '0'&&s[i] <= '9') { o += s[i]; n++; i++; } else if (s[i] == '.' && (!dot)) { o += s[i]; n++; i++; dot = true; } } if (o[n - 1] == '.')n--;//最后不能是小数点 while (o[n - 1] == '0' && dot)n--;//小数点后不能是连续的零 if (first)first = false; else cout << " ";//输出整个数字串 for (int j = 0; j < n; j++)cout << o[j]; o = ""; n = 0;//数字串清零,这时的i在非数字位 } else if (s[i] == '0'&&s[i + 1] != '.' && (s[i + 1] < '0' || s[i + 1] > '9'))//输出单个0 { if (first)first = false; else cout << " ";//输出整个数字串 cout << s[i]; } } cout << endl; return 0; }