现在的位置: 首页 > 综合 > 正文

zoj 2476 Total Amount

2012年08月25日 ⁄ 综合 ⁄ 共 919字 ⁄ 字号 评论关闭
//这题主要是大数相加!不过要注意,有小数点!输出的格式也非常严格!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 
*/



抱歉!评论已关闭.