前言
学习了C++一段时间后,尝试开始解题(白给)。
基础顺序结构题
1.老规矩开局先来个hello world
#include <iostream>
using namespace std;
int main()
{
cout<<"hello world!"<<endl;
system("pause");
}
2.编写程序完成温度转换。要求程序运行时从键盘输入任意的华氏温度值(浮点型),将其转换成摄氏温度值并输出(结果保留2位小数)。
提示:C:摄氏 F:华氏。C = 5/9*(F-32)。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float c,f;
cin>>f;
c=5.0/9*(f-32);
cout<<fixed<< setprecision(2)<<c<<endl;
system("pause");
}
这里遇到一个问题,一般来说,cout不能输出小数点,但结合<iomanip>
这个库,可以在cout输出中将代码<<fixed<< setprecision(2)
加入在对应想取小数点后两位的量前面。
同时,也可以使用printf的输出方法
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float c,f;
cin>>f;
c=5.0/9*(f-32);
printf("%0.2f",c);
system("pause");
}
3.编写程序求三角形面积,要求程序运行时从键盘依次输入三角形的三个边长(浮点型),计算输出三角形的面积。
提示:设三边长为a,b,c,p=(a+b+c)/2,则三角形面积平方=p*(p-a)(p-b)(p-c);开平方可用数学函数sqrt()。
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float a,b,c,p,s,h;
cin>>a>>b>>c;
p=(a+b+c)/2;
h=p*(p-a)*(p-b)*(p-c);
s=sqrt(h);
cout<<s<<endl;
system("pause");
}
同样的C++也可以调用数学库,并且和C语言使用数学库并无区别。
选择结构基础题
1.编写程序,要求程序运行时,从键盘输入某个学生某门课程的成绩(0-100间的整数),当成绩高于90分时,输出A;成绩在80-89之间,输出B;成绩在70-79之间,输出C;成绩在60-69之间,输出D;成绩在0-59之间,输出E。输入成绩不在0-100范围,输出error。
#include <iostream>
using namespace std;
int main()
{
int score;
cin>>score;
if(score>=0&&score<=100)
{
if(score>=90)
{
cout<<"A"<<endl;
}
else
{
if(score<=89&&score>=80)
{
cout<<"B"<<endl;
}
else
{
if(score>=70&&score<=79)
{
cout<<"C"<<endl;
}
else
{
if(score>=60&&score<=69)
{
cout<<"D"<<endl;
}
else
{
cout<<"E"<<endl;
}
}
}
}
}
else
{
cout<<"error!"<<endl;
}
system("pause");
}
基本与C语言保持同步。
后语
本周基础学习了这里,继续gogogogo!