pta 1001 A+B Format (整数转换为字符串)

1001 A+B Format (20)(20 分)

Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input

-1000000 9

Sample Output

-999,991

 【分析】

  1. 要用到整数转换成字符串的相关语句,下面做一下小结
    1. C++中的stringstream  (适用于少量数据)

      #include <bits/stdc++.h>
      using namespace std;
      int main(){
          int a = 1000;
          double b=100.99;
          string res1,res2;
          stringstream ss1,ss2;
          ss1 << a;
          ss1 >> res1;//或者 res = ss1.str();
          cout<<res1<<endl;
          ss2 << b;
          ss2 >> res2;//或者 res = ss2.str();
          cout<<res2<<endl;
          return 0;
      }

      输出:

      1000
      100.99

      其他方法:

      1. https://blog.csdn.net/michaelhan3/article/details/75667066/

      2. http://www.cnblogs.com/luxiaoxun/archive/2012/08/03/2621803.html

    2. 本题代码:注意负号的处理

      #include<bits/stdc++.h> 
      using namespace std;
      int main()
      {
      	int a,b;
      	while(~scanf("%d%d",&a,&b))
      	{
      		int x=a+b;
      		string res;
      		stringstream ss;
      		ss<<x;
      		ss>>res;
      		//cout<<res<<endl;
      		int l=res.length();
      		for(int i=0;i<l;i++)
      		{
      			cout<<res[i];
      			if(res[i]=='-')continue;
      			if((l-1-i)%3==0&&i!=(l-1))cout<<",";	
      		}
      		cout<<endl;
      	}
      	
      	
      	return 0;
      }

猜你喜欢

转载自blog.csdn.net/qq_38735931/article/details/81356949