1001 A+B Format (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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10
6
≤a,b≤10
6
. The numbers are separated by a space.
Output Specification:
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
解题
计算sum后转化成string类型(利用to_string()函数);
按顺序输出,当剩余数字还剩3的倍数个时,输出“,”,最后一个数字不输出逗号;
#include<iostream>
#include<string>
using namespace std;
int a,b;
int Sum;
void input(){
cin>>a>>b;
Sum=a+b;
}
string Result;
void process()
{
Result = to_string(Sum); //to_string 函数
int len=Result.length(); //.length() 成员函数
for(int i=0;i<len;i++)
{
cout<<Result[i];
if(Result[i]=='-') continue;
if((len-1-i)%3==0&&i!=len-1)
//len-i-1为剩余数字个数,若剩余个数可以被3整除——则输出逗号
//最后一个不用
cout<<",";
}
}
int main()
{
input();
process();
}
关键
to_string函数把int转化为string;
计算输出逗号的时机,对’-‘的跳过处理,以及最后一个数后不输出逗号;
1002 A+B for Polynomials (25分)
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N
1
a
N
1
N
2
a
N
2
… N
K
a
N
K
where K is the number of nonzero terms in the polynomial, N
i
and a
N
i
(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N
K
<⋯<N
2
<N
1
≤1000.
Output Specification:
For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
解题关键
指数相同,系数相加;
若系数相加后为0,则不输出,且也不计数!
1.每一项的结构函数
#include<iostream>
#include<algorithm>
using namespace std;
struct Num{
int exp;
double coef;
};
2.输入
分别保存在两个列表中
const int MAXK=11;
Num poly1[MAXK];
Num poly2[MAXK];
int k1,k2;
void input()
{
cin>>k1;
for(int i=0;i<k1;i++)
cin>>poly1[i].exp>>poly1[i].coef;
cin>>k2;
for(int i=0;i<k2;i++)
cin>>poly2[i].exp>>poly2[i].coef;
}
3.相加操作
Num result[2*MAXK];
int Count=0;
void ADD()
{
int i=0,j=0;
while(i<k1&&j<k2)
{
if(poly1[i].exp>poly2[j].exp)
result[Count++]=poly1[i++];
if(poly1[i].exp<poly2[j].exp)
result[Count++]=poly2[j++];
if(poly1[i].exp==poly2[j].exp)
{
Num temp;
temp.exp=poly1[i].exp;
temp.coef=poly1[i].coef+poly2[j].coef;
if(temp.coef!=0) //这里若为0则不加入结果列表中
result[Count++]=temp;
i++;j++;
}
}
while(j<k2) result[Count++]=poly2[j++];
while(i<k1) result[Count++]=poly1[i++];
}
4.主函数
int main()
{
input();
ADD();
cout<<Count;
for(int i=0;i<Count;i++)
printf(" %d %.1f",result[i].exp,result[i].coef);
}