杭电ACM刷题(1):1002,A + B Problem II
最近忙于考試復(fù)習(xí),沒有多少可供自己安排的時(shí)間,所以我利用復(fù)習(xí)之余的空閑時(shí)間去刷刷杭電acm的題目,也當(dāng)對(duì)自己編程能力的鍛煉吧。
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
Output
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line is the an equation “A + B = Sum”, Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
程序思路:
程序:
#include "stdio.h" #include "string.h"#pragma warning(disable:4996)int main() {char a_str[1000] = { 0 }, b_str[1000] = {0};int a_num[1000], b_num[1000];int a_len, b_len, max_len;int n;int i, j, k;int temp;scanf("%d", &n);if (n < 1 || n>20)return -1;for (i = 1;i <= n;i++){//步驟1scanf("%s%s", a_str, b_str);a_len = strlen(a_str);b_len = strlen(b_str);//步驟2temp = 0;for (j = a_len - 1;j >= 0;j--){a_num[temp++] = a_str[j] - '0';}temp = 0;for (k = b_len - 1;k >= 0;k--){b_num[temp++] = b_str[k] - '0';}//步驟3if (a_len > b_len){for (j = b_len;j <= a_len;j++){b_num[j] = 0;}a_num[a_len] = 0;}else if (a_len < b_len){for (j = a_len;j <= b_len;j++){a_num[j] = 0;}b_num[b_len] = 0;}else{a_num[a_len] = 0;b_num[b_len] = 0;}max_len = (a_len >= b_len) ? a_len : b_len;//步驟4for (j = 0;j <= max_len;j++){ a_num[j] += b_num[j];if (a_num[j] >= 10){a_num[j] -= 10;a_num[j + 1] += 1;}}//步驟5printf("Case %d:\n", i);printf("%s + %s = ", a_str, b_str);if (a_num[max_len] == 0){for (j = max_len - 1;j >= 0;j--)printf("%d", a_num[j]);}else{for (j = max_len;j >= 0;j--)printf("%d", a_num[j]);}if (i != n)printf("\n\n");elseprintf("\n");}return 0; }備注:
由于我是在visual studio 2015環(huán)境中調(diào)試這段程序的,在使用“scanf”函數(shù)時(shí)會(huì)報(bào)錯(cuò)。因?yàn)樵趍icrosoft的Visual Studio進(jìn)行編譯時(shí),會(huì)提示“scanf”函數(shù)是不安全的,建議使用“scanf_s”函數(shù)來代替“scanf”。“scanf_s”函數(shù)在使用時(shí),如果需要輸入字符串?dāng)?shù)組,還需要指定邊界,即數(shù)組的長度。一般情況下使用“scanf_s”函數(shù)就能替代“scanf”函數(shù)了,但是這題中卻不行,因?yàn)槲覀円矡o法確定輸入數(shù)組的長度。所以得出的結(jié)論就是,繼續(xù)使用“scanf”函數(shù),在程序加入這段代碼:
這樣就可以照常在程序中使用“scanf”而不報(bào)錯(cuò)了。
運(yùn)行結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的杭电ACM刷题(1):1002,A + B Problem II的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数字图像处理实验(5):Proj03-0
- 下一篇: 数字图像处理实验(5):PROJECT