一、平方根
#include <iostream>
#include <math.h>//头文件
using namespace std;
int main()
{
int a;cin>>a;
double b=sqrt(a);//函数
cout<<(int)b;
}
二、上下取整
题目描述
任意给出一个小数,编程求不小于它的最小整数与不大于它的最大整数。 即求出这个小数往下取整与往上取整的值。
输入描述:
输入一行,包含一个浮点数a
输出描述:
输出两行,第一行表示a往下取整,第二行表示a往上取整。
示例1
输入
3.5
输出
3 4
方法一:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float a;cin>>a;
int b=(int)(ceil(a));
if(b-a==0)cout<<b<<endl<<b;
else cout<<b-1<<endl<<b;
}
方法二:
#include <iostream>
using namespace std;
int main()
{
float a;cin>>a;
int a1=a;
if(a1-a==0){
cout<<a1<<endl<<a1;
}
else{
if(a>0){cout<<a1<<endl<<a1+1;}
else {cout<<a1-1<<endl<<a1;}
}
}
三、整数与字符串的sstream转换方法
一、string转int
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;string str;stringstream ss;
cin >> x; ss << x;ss >> str;
cout << str; return 0;
}
二、int转string
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;string str; stringstream ss;
cin >> str; ss << str;
ss >> x; cout << x;
return 0;
}
四、保留小数
输入两个整数a, b, 输出a除以b的值,保留三位小数
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int a,b;cin>>a>>b;float c=1.0*a/b;
cout<<setiosflags(ios::fixed)<<setprecision(3)<<c;
return 0;
}
五、对齐输出
题目描述
牛牛渐入佳境,他准备做一个加法模拟器来玩玩,输入两个数,分别打印这两个数的横式和竖式运算式子。
输入描述:输入两个整数a, b 以空格隔开0 <= a, b <= 1000
输出描述:第一行打印横式运算式子,接下来四行打印竖式运算式子
示例1
输入
45 237
输出
45+237=282
45
+ 237
-------
282
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a,b;cin>>a>>b;
cout<<a<<"+"<<b<<"="<<a+b<<endl;
printf("%7d\n", a);
cout<<"+";
printf("%6d\n", b);
cout<<"-------"<<endl;
printf("%7d\n", a+b);
}