我解決了這個問題,首先計算兩個給定數字的長度,並將數字較少的數字(如果存在的話)對齊到一個新的數組中然後我想將每兩個對齊的元素(模數爲10)的總和保存到一個新的數組中,同時檢查這個數組是否與數字總和大於10--只是基本的總和。現在問題發生在添加兩個元素到aplusb整數,我試圖用寫入來修復它作爲字符數組添加兩個數字[1,10^10000] - C
int aplusb = (lengthA[max-i]-'0') +(temp[max-i]-'0');
但它不起作用。我被卡住了,我不知道該怎麼做。請幫忙。
整個代碼:
#include <stdio.h>
#include <math.h>
int main(){
char a[10000];
char b[10000];
scanf("%s %s", &a, &b);
char sum[10000];
int lengthA = 0;
int lengthB = 0;
int i = 0;
while(a[i]){
i++;
} lengthA = i;
i = 0;
while(b[i]){
i++;
} lengthB = i;
char temp[10000];
int aplusb;
int carry = 0;
int max = lengthA;
int difference = abs(lengthA - lengthB);
if(lengthA>lengthB){
for(i=0; i<lengthA; i++){
temp[i+difference]=b[i];
}
for(i=0; i<=max; i++){
aplusb = lengthA[max-i]+temp[max-i]; //<-- this is the problematic line
if(carry = 1) aplusb++;
if(aplusb>9){
carry = 1;
aplusb%=10;
}
sum[i]=aplusb;
}
}
for(i=0; i<=max; i++){
printf("%c", sum[i]);
}
/*
if(lengthB>lengthA){
max = lengthB;
for(i=0; i<lengthB; i++){
temp[i+difference]=a[i];
}
}*/
return 0;
}
'10^10000'是'10010'。一個'int'就足夠了。 – Olaf
'if(carry = 1)'是賦值。更改爲'if(carry == 1)' –
我的意思是10的權力10000 @Olaf – Vid