PAT甲级真题

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

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

1
-1000000 9

Sample Output

1
-999,991
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000B
判题程序
Standard
作者
CHEN, Yue

解题思路

简单的计算两个数之和,然后三位一组用逗号分隔开输出(只有当结果低于四位的时候才不用分隔)

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main() {
int a, b, sum, temp;
scanf("%d %d",&a,&b);
sum = a + b;
temp = abs(sum);
if (temp < 1000)
printf("%d",sum);
else if (temp < 1000000)
printf("%d,%03d", sum / 1000, temp % 1000);
else
printf("%d,%03d,%03d",sum/1000000,temp/1000%1000,temp%1000);
system("pause");
return 0;
}

涉及知识

提取数字相应的位数

这里使用的是直接按三位一组提取的,当然也可以一位一位提取出来,再进行输出

设一个数为n,则在C语言中其个位、十位、百位、千位依次这样计算:n/1%10,n/10%10,n/100%10,n/1000%10

数字格式化

当输出数字不足三位时,在前面补0

%03d 输出三位宽度的整数, 不足时前补0
%3d 输出三位宽度的整数, 不足时后补空格
%-3d 输出三位宽度的整数, 不足时前补空格

1002. A+B for Polynomials (25)

题目描述

This time, you are supposed to find A+B where A and B are two polynomials.

Input

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 … NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < … < N2 < N1 <=1000.

Output

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

1
2
2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output

1
3 2 1.5 1 2.9 0 3.2
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

解题思路

题目已说明多项式系数是有限的,因此使用一个数组A来存储多项式,A[i]就表示幂次为i的项的系数。输入第一个多项式后, 再将第二个多项式直接加到第一个多项式上面,统计非零项输出即可。

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<stdio.h>
#include<stdlib.h>
int main() {
int n1, n2, temp, count = 0;
double A[1001],k2;
scanf("%d",&n1);

for (int i = 0; i < 1001; i++) { //初始化数组
A[i] = 0;
}
for (int i = 0; i < n1; i++) { //输入第一个多项式
scanf("%d", &temp);
scanf("%lf",&A[temp]);
count += 1;
}
scanf("%d", &n2);
for (int i = 0; i < n2; i++) { //将第二个多项式直接加到第一个多项式上,并统计非零项数
scanf("%d", &temp);
scanf("%lf", &k2);
if (A[temp] == 0)
count++;
A[temp] += k2;
if (A[temp] == 0)
count--;
}
printf("%d",count);
for (int i = 1000; i >= 0;i--) //输出结果
if (A[i] != 0) {
printf(" %d %.1f",i,A[i]);
}

system("pause");
return 0;
}

注意事项

输入

题目给出输入是非零项,且系数是浮点类型的。

输出

题目要求输出非零项,要按从大到小的顺序,且系数保留一位小数。注意两个多项式在相加时系数可能会变成零,此时该项不输出。