北京理工大学计算机学院复试上机题目
由于编者水平有限,如有错误,请多多包涵。欢迎各位指正,转载请注明,谢谢合作!
1.输入球的中心点和球上某一点的坐标,计算球的半径和体积。
#include<iostream>
#include<math.h>
#define PI 3.1415926
using namespace std;
int main(){
double x1,y1,x2,y2,r;
cout<<"请输入球心坐标:";
cin>>x1>>y1;
cout<<"请输入圆上一点坐标::";
cin>>x2>>y2;
r=sqrt(pow(x1-x2,2)+pow(y1-y2,2));
cout<<"半径长度为:"<<r<<endl;
cout<<"体积为:"<<PI*pow(r,3)*4/3.0<<endl;
return 0;
}
2.手工建立一个文件,文件种每行包括学号、姓名、性别和年龄。每一个属性使用空格分开。文件如下:
01 李江 男 21
02 刘唐 男 23
03 张军 男 19
04 王娜 女 19
根据输入的学号,查找文件,输出学生的信息。
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(){
int t,no,age;
string name,sex;
ofstream outfile("message.txt");
cout<<"输入学生信息(学号、姓名、性别、年龄,0结束):";
while(1){
cin>>no;
if(no==0)
break;
cin>>name>>sex>>age;
if(age<1){
cout<<"年龄不合法!"<<endl;
continue;
}
outfile <<no<<" "<<name<<" "<<sex<<" "<<age<<endl;
}
// 查询
while(1){
cout<<"请输入需要查找的学生的学号:";
cin>>t;
ifstream infile("message.txt");
bool flag=false;
while(!infile.eof()){
infile>>no>>name>>sex>>age;
if(infile.fail()){
flag=true;
break;
}
if(no==t){
if(no<10)
cout<<0;
cout<<no<<" "<<name<<" "<<sex<<" "<<age<<endl;
break;
}
}
if(infile.eof()||flag)
cout<<"查无此人!"<<endl;
}
return 0;
}
3.输入年月日,计算该天是本年的第几天。例如1990年 9 月 20 日是 1990 年的第 263 天,2000年 5 月 1 日是 2000 年第 122 天。(闰年:能被 400整除,或能被 4 整除但不能被 100 整除。每年 1、3、5、7、8、10 为大月)。
#include<iostream>
#define ISYEAR(x) x%100!=0 && x%4==0 || x%400==0?1:0 // 定义宏,判断是否是闰年
using namespace std;
/**
* 还是采取预处理的思想,用空间换取时间
*/
int dayOfMonth[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};
class Date{
public:
int year;
int month;
int day;
Date() {}
Date(int y,int m,int d) {
year=y;
month=m;
day=d;
}
bool nextDate(){
day++;
if(day>dayOfMonth[month][ISYEAR(year)]){
day=1;
month++;
if(month>12)
return true;
}
return false;
}
};
int main(){
int bufP[13][32]; // 平年
int bufR[13][32]; // 闰年
int y,m,d;
// 初始化平年
int count=1;
Date d1(1,1,1);
while(1){
bufP[d1.month][d1.day]=count++;
if(d1.nextDate())
break;
}
count=1;
Date d2(4,1,1);
// 初始化闰年
while(1){
bufR[d2.month][d2.day]=count++;
if(d2.nextDate())
break;
}
while(1){
cout<<"输入日期,以空格为间隔:";
cin>>y>>m>>d;
if(y<1||m<1||m>12||d<1||d>dayOfMonth[m][ISYEAR(y)]){
cout<<"日期无效,请重新输入!"<<endl;
continue;
}
cout<<"这是"<<y<<"年的第";
if(ISYEAR(y))
cout<<bufR[m][d];
else
cout<<bufP[m][d];
cout<<"天。"<<endl;
}
return 0;
}