求平方根,输入一个实数x 计算并输出平方根(要求保留2位小数)
本题考察:
①、平方根函数的使用,函数库的调用。
②、结果保留两位小数的使用,函数库的调用。
#include <iostream>
#include <cmath>
#include<iomanip>
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
cout<<"请输入一个实数:";
double x;
cin>>x;
double s = sqrt(x);
cout<<x<<"的平方根为:"<<s<<endl;
cout<<x<<"的平方根为:"<<setiosflags(ios::fixed)<<setprecision(2)<<s<<endl;//引用头文件#include<iomanip>
return 0;
}
输出结果:


说明:
对比上面每一张图片中的输出结果,普通的输出是不能精确输出保留的小数的位数,所以想要精确到保留两位小数,则需要使用setiosflags(ios::fixed),setprecision(2)。而且必须要声明头文件(函数库)#include <iomanip>
C++保留小数位数的使用请点击我!!!
对于求一个数的平方根,要使用sqrt()函数。对于该数学函数的使用,必须要声明头文件(函数库) #include <cmath>
