✔ 最佳答案
#include <iostream>
#include "stdlib.h"
using namespace std;
void main(void)
{
int i, xlen, ylen;
char* c = new char[1];
char* input = new char[255];
cout << "請連續輸入兩個整數" << endl;
cin >> input;
xlen = strlen(input);
int* x = new int[xlen];
for (i=0; i<xlen; i++)
{
c[0] = input[xlen - i - 1];
x[i] = atoi(c);
}
cin >> input;
ylen = strlen(input);
int* y = new int[ylen];
for (i=0; i<ylen; i++)
{
c[0] = input[ylen - i - 1];
y[i] = atoi(c);
}
cout << "第一個整數為: ";
for (i=xlen; i>0; i--)
cout << x[i-1];
cout << endl;
cout << "第二個整數為: ";
for (i=ylen; i>0; i--)
cout << y[i-1];
cout << endl;
cout << "兩數和=";
int len = max(xlen, ylen);
int* sum = new int[len+1]; // 考慮進位情況..所以要多給一個空間
for (i=0; i<len+1; i++) sum[i] = 0;
for (i=0; i<len; i++)
{
int j = 0;
if (i <= xlen) j += x[i];
if (i <= ylen) j += y[i];
if (j >= 10) // 考慮相加大於等於10要進位
{
sum[i+1] += 1;
j -= 10;
}
sum[i] += j;
}
if (sum[len]==1) cout << 1;
for (i=len-1; i>=0; i--)
cout << sum[i];
cout << endl;
delete [] c;
delete [] x;
delete [] y;
delete [] sum;
system("pause");
}