double a=50.25;
int res1=floor(a);//向下取整函数,res1=50
int res2=ceil(a);//向上取整函数,res2=51
int res3=round(a);//四舍五入函数,res3=51
2. 保留几位小数
重写函数
#include<iostream>
#include <iomanip>
#include <sstream>
using namespace std;
//四舍五入
string round(double num,int bits)
{
//方法一:矩阵快速幂
long long ans = 1;
int n = bits;
int base = 10;
while (n)
{
if (n & 1)
ans = ans * base;
base = base * base;
n >>= 1;
}
//方法二:直接pow
/*double ans = pow(10, bits);*/
num = round(num*ans) / ans;
stringstream ss;
ss << fixed << showpoint << setprecision(bits) <<num<< endl;
string s;
ss >> s;
return s;
}
//向下取小数
string floor(double num, int bits)
{
long long ans = 1;
int n = bits;
int base = 10;
while (n)
{
if (n & 1)
ans = ans * base;
base = base * base;
n >>= 1;
}
/*double ans = pow(10, bits);*/
num = floor(num*ans) / ans;
stringstream ss;
ss << fixed <<showpoint<< setprecision(bits) << num;
string s;
ss >> s;
return s;
}
//向上取小数
string ceil(double num,int bits)
{
long long ans = 1;
int n = bits;
int base = 10;
while (n)
{
if (n & 1)
ans = ans * base;
base = base * base;
n >>= 1;
}
/*double ans = pow(10, bits);*/
num = ceil(num*ans) / ans;
stringstream ss;
ss << fixed << showpoint << setprecision(bits) << num;
string s;
ss >> s;
return s;
}
int main() {
double a = 50.23;
double b = 50.25;
cout <<ceil(a,1) <<endl;
cout << floor(a, 1) << endl;
cout << round(a, 1) << endl;
}