code1(WA):
#include<iostream>
#include<cstring>
#include<iomanip>
using namespace std;
int main()
{
char number1[300];
char number2[300];
while(cin >> number1)
{
cin >> number2;
int temp1[300]={0};
int temp2[300]={0};
int len1=strlen(number1)-1;
int len2=strlen(number2)-1;
int index1=0;
int index2=0;
int i;
for(i=len1;i>=3;i-=4)
{
temp1[index1]=number1[i]-'0'+(number1[i-1]-'0')*10+(number1[i-2]-'0')*100+(number1[i-3]-'0')*1000;
index1++;
}
int k=0;
while(k<=i)
{
temp1[index1]*=10;
temp1[index1]+=number1[k]-'0';
k++;
}
for(i=len2;i>=3;i-=4)
{
temp2[index2]=number2[i]-'0'+(number2[i-1]-'0')*10+(number2[i-2]-'0')*100+(number2[i-3]-'0')*1000;
index2++;
}
k=0;
while(k<=i)
{
temp2[index2]*=10;
temp2[index2]+=number2[k]-'0';
k++;
}
int product[300]={0};
int j;
for(i=0;i<=index2;i++)
{
int carry=0;
j=i;
for(k=0;k<=index1;k++,j++)
{
product[j]+=(temp1[k]*temp2[i]+carry);
carry=product[j]/10000;
if(product[j]>10000 && k != index1)
product[j]%=10000;
}
}
j--;
while(product[j] == 0)
j--;
cout << product[j--];
while(j>=0)
{
cout << setw(4) << setfill('0') << product[j];
j--;
}
cout << endl;
}
// system("pause");
return 0;
}
code2(AC):
#include<iostream>
#include<cstring>
#include<iomanip>
using namespace std;
int main()
{
char number1[300];
char number2[300];
while(cin >> number1)
{
cin >> number2;
int temp1[300]={0};
int temp2[300]={0};
int len1=strlen(number1)-1;
int len2=strlen(number2)-1;
int index1=0;
int index2=0;
int i;
if((number1[0] == '0' && number1[1] == '\0') || (number2[0] == '0' && number2[1] == '\0'))
{
cout << 0 << endl;
continue;
}
for(i=len1;i>=3;i-=4)
{
temp1[index1]=number1[i]-'0'+(number1[i-1]-'0')*10+(number1[i-2]-'0')*100+(number1[i-3]-'0')*1000;
index1++;
}
int k=0;
while(k<=i)
{
temp1[index1]*=10;
temp1[index1]+=number1[k]-'0';
k++;
}
for(i=len2;i>=3;i-=4)
{
temp2[index2]=number2[i]-'0'+(number2[i-1]-'0')*10+(number2[i-2]-'0')*100+(number2[i-3]-'0')*1000;
index2++;
}
k=0;
while(k<=i)
{
temp2[index2]*=10;
temp2[index2]+=number2[k]-'0';
k++;
}
int product[300]={0};
int j;
for(i=0;i<=index2;i++)
{
int carry=0;
j=i;
for(k=0;k<=index1;k++,j++)
{
product[j]+=(temp1[k]*temp2[i]+carry);
carry=product[j]/10000;
if(product[j]>10000)
{
if(k == index1)
product[j+1]=product[j]/10000;
product[j]%=10000;
}
}
}
while(product[j] == 0)
j--;
cout << product[j--];
while(j>=0)
{
cout << setw(4) << setfill('0') << product[j];
j--;
}
cout << endl;
}
system("pause");
return 0;
}
我只是把code1的藍色部分改成code2的藍色部分
想請教有什麼差別?
是因為相乘再相加後有可能會爆掉?!
另外,想請教說code2的紅色部分
當我沒加上這個判斷測試資後顯示我output是1
可是我在Visual studio compile 是一個負值
為什麼他是顯示出1呢?
謝謝:)