实现函数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;
}