2003年北理复试上机题目
1、输入球的中心点和球上某一点的坐标,计算球半径和体积。
注意:(4/3)会先转换为int型,变为1而不是1.3333...,应写为(4/3.0),或者/3放在表达式最后
#include<iostream> #include<cmath> using namespace std; int main() { double x, y, z, a, b, c; cout << "请输入球心坐标:" << endl; cin >> x >> y >> z; cout << "请输入球上某一点坐标:" << endl; cin >> a >> b >> c; double r = sqrt((x - a)*(x - a) + (y - b)*(y - b) + (z - c)*(z - c)); double V = 3.14 * r * r * r * 4 / 3; cout << "球半径为:" << r << endl; cout << "球体积为:" << V << endl; return 0; }
2、手工建立一个文件,文件中每行包括学号、姓名、性别和年龄。每一个属性使用空格分开。文件如下:
01 李江 男 21
02 刘唐 男 23
03 张军 男 19
04 王娜 女 19
根据输入的学号,查找文件,输出学生的信息。
cin.eof():当流输入为文件结束符时eof()为1,否则为0;
cin.fail():判断流操作是否失败(比如变量类型不匹配,或者变量数目不匹配等),如果输入失败就会返回true。
#include<iostream> #include<cstring> #include<fstream> using namespace std; struct Student { char id[5]; char name[50]; char sex[5]; int age; }; int main() { Student s; char x[5]; ofstream out("sf1.txt"); out << "01 李江 男 21" << endl; out << "02 刘唐 男 23" << endl; out << "03 张军 男 19" << endl; out << "04 王娜 女 19" << endl; cout << "请输入要查找的学生学号:"; cin >> x; ifstream in("sf1.txt"); bool flag = false; while (!in.eof()) { in >> s.id >> s.name >> s.sex >> s.age; if (in.fail())break; if (strcmp(x, s.id) == 0) { flag = true; cout << s.id << " " << s.name << " " << s.sex << " " << s.age << endl; } } if(in.eof() && flag == false)cout << "无此学生信息。" << endl; system("pause"); return 0; }
3、输入年月日,计算该天是本年的第几天。例如1990 年 9 月 20 日是 1990 年的第 263 天,2000年 5 月 1 日是 2000 年第 122 天。(闰年:能被 400整除,或能被 4 整除但不能被 100 整除。每年 1、3、5、7、8、10 为大月)
#include<iostream> using namespace std; int month[13][2] = { 0,0,31,31,28,29,31,31,30,30,31,31,30,30,31,31,31,31,30,30,31,31,30,30,31,31 }; bool isLeapYear(int x) { return (x % 4 == 0 && x % 100 != 0) || x % 400 == 0; } int Date(int y, int m, int d) { int mm = 1, dd = 1, ans = 1; while (mm != m || dd != d) { dd++; ans++; if (dd > month[mm][isLeapYear(y)]) { dd = 1; mm++; if (mm > 12) return -1; } } return ans; } int main() { int y, m, d; cout << "请输入要查询的日期,如1998 7 1:" << endl; cin >> y >> m >> d; int ans = Date(y, m, d); if (ans == -1)cout << "非法日期。" << endl; else cout << "该天是本年的第" << ans << "天。" << endl; return 0; }

浙公网安备 33010602011771号