C语言oj中a b怎么做,【HDUOJ】第1002题 A + B Problem II 纯C语言解法
【HUDOJ-1002】
1.原題:
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
21 2112233445566778899 998877665544332211
Sample Output
Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110
Author
Ignatius.L
2:解題思路及技巧:
在計算機中,當要表示的數據超出計算機所使用的數據的表示范圍時,則產生數據的溢出。溢出導致大數相加計算錯誤,此時就需要一種新的辦法。由于大數無法直接保存,我們采用字符串的方式保存大數的每一位,然后將字符轉換為數字型,類似于小學加法算式將兩個數對應位相加(大于十進一),這里需要注意以下幾點:
a.字符轉數字:遍歷數組對每一位減‘0’得到對應數字的integer值。
b.要初始化所有數組的所有元素為0以便后續的計算,這里采用memset函數將數組的所有元素初始化為0。
c.存數時需要倒序輸入便于計算。
d.memset函數:memset是計算機中C/C++語言函數。將s所指向的某一塊內存中的后count個字節的內容全部設置為ch指定的ASCII值, 第一個值為指定的內存地址,塊的大小由第三個參數指定,這個函數通常為新申請的內存做初始化工作, 其返回值為s。
void*?memset(void*?s,intch,size_tcount)
{
char*xs?=?(char*)?s;
while(count--)
*xs++?=?ch;
returns;
}
3:完整代碼(已AC)
#include #include int main(int argc,char const*argv[])
{
int T;
char m[1001],n[1001];
scanf("%d",&T);
int cnt=1;
int k=T;
while(k--){
int a[1001],b[1001],c[1001];
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
//初始化數組元素為零
int l,len;
scanf("%s",&m);
scanf("%s",&n);
//讀入字符數組
int len1=strlen(m),len2=strlen(n);
//保存字符型數字的長度
int max=(len1>len2)?len1:len2;
for(int i=0;i=10){
c[len]+=a[len]+b[len]-10;
c[len+1]++;
}
else
c[len]+=a[len]+b[len];
}
for(l=len;l=10){
c[l]+=a[l]-10;
c[l+1]++;
}
else
c[l]+=a[l];
}
printf("Case %d:\n",cnt);
for(int i=len1-1;i>=0;i--)
printf("%d",a[i]);
printf(" + ");
for(int i=len2-1;i>=0;i--)
printf("%d",b[i]);
printf(" = ");
for(int x=l-1;x>=0;x--)
printf("%d",c[x]);
if(cnt++
總結
以上是生活随笔為你收集整理的C语言oj中a b怎么做,【HDUOJ】第1002题 A + B Problem II 纯C语言解法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 矫正牙齿花多少钱啊?
- 下一篇: 计算机二级c语言选择题范围,计算机二级C