您的位置:首页 > 其它

zoj 2476 Total Amount

2012-03-31 10:41 225 查看
//这题主要是大数相加!不过要注意,有小数点!输出的格式也非常严格!WA了很多次,因为没有考虑到全是0.00相加的情况!
#include "iostream"
#include "string"
#include "memory.h"
#include "cctype"
#include "algorithm"
using namespace std;

int temp[20], ans[20];

int main()
{
int N, i, j, k, len, count;
string input, output;
while (cin >> N && N)
{
output = "";
memset(ans, 0, sizeof(ans));
for (i = 0; i < N; i++)
{
cin >> input;
memset(temp, 0, sizeof(temp));
len = input.length();
for (j = 0, count = 0; j < len; j++)//将字符转换为数字
{
if (isdigit(input[len-1-j]))
{
temp[count] = input[len-1-j] - 48;
count++;
}
}
for (j = 0; j < 20; j++)//大数相加的一般做法!
{
ans[j] = temp[j] + ans[j];
ans[j+1] += ans[j] / 10;
ans[j] = ans[j] % 10;
}

}
for (j = 0; j < 20; j++)
if (ans[20-1-j] != 0)
break;
k = 20-1-j;
k = k >= count-1 ? k : count-1;//判断是否忽略了前导0,这个需要特别留意,很容易出错!
for (j = 0, i = 1; j <= k; j++, i++)//格式的输出!
{
output += ans[j] + 48;
if (j == 1)
{
output += ".";
i = 0;
}
if (i%3 == 0 && i != 0 && i != k-1)
{
output += ",";
}
}
output += "$";
reverse(output.begin(), output.end());
cout << output << endl;
}
return 0;
}
/*
3
$11,999,999.99
$99,999,999.99
$111,999,999.11
3
$0.00
$0.00
$0.00
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: