格式化除法

实现函数string FormattedDivision(num1,num2) ,运算num1/num2,以三位分节法表示整数部分,并保留小数点后4位,若运算结果的小数部分不满4位,则以0填充,最终结果以string类型返回。

例子:

输入:num1=123456789,num2=10000   

输出:12,345.6789

输入:num1=10000 num2=2;

输出:5,000.0000

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

string FormattedDivision(int num1, int num2) {
	string result;
	stringstream ss;
	int integer;
	double fraction;
	string temp1, temp2;
	integer = num1 / num2;
	ss << integer;
	ss >> temp1;
	int count = 0;
	int length = temp1.length();
	string::reverse_iterator iter = temp1.rbegin();
	if (temp1.length() > 3)
	{
		
		while (iter != temp1.rend())
		{
			count++;
			if (count % 3 == 0)
			{
				temp1.insert(length - count, ",");
			}
			iter++;
		}
	}
	double a = static_cast<double>(num1);
	double b = static_cast<double>(num2);

	if (integer == 0)
	{
		fraction = a / b;
	}
	else
	{
		fraction = a / b - integer;
	}
	ss.clear();
	ss << fraction;
	ss >> temp2;
	if (temp2.length() >= 6)
		temp2.assign(temp2.begin() + 2, temp2.begin() + 6);
	else
	{
		while (temp2.length()<6)
		{
			temp2 += '0';
		}
		temp2.assign(temp2.begin() + 2, temp2.begin() + 6);
	}
	result = temp1 + "." + temp2;
	return result;
}

int main() {

	// keep this function call here

	cout << FormattedDivision(123456789, 10000) << endl;
	cout << FormattedDivision(10000, 2) << endl;

	return 0;

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值