C++小数处理

小数处理

1. 三个取整函数
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;
		
}
  • 输出时处理
    //fixed保证小数按原始小数输出
    //showpoint保证5能输出5.0000
    //setprecision保证精度(四舍五入)
    //只能处理四舍五入
    double num=50.25;
    cout << fixed<< showpoint << setprecision(4) << num <<endl;//50.2500
    
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值