[C++] 動態陣列 相加 的問題~~急!!>

2009-04-02 9:39 am
如果要用 動態陣列 來存放任意位數的整數

(ex:整數1234用陣列 a 存放,其中個位數4 放在 a[0],十位數 3放在 a[1],百位數 2放在 a[2],以此類推)

請問怎麼設計ㄧ個程式來做 "兩個任意位數的整數相加工作" ?

而且整數要以文字(character)的方式輸入,用手算的加法程序來進行整數相加,最後請輸出這兩個整數及其整數相加的結果。


麻煩會的大大能敎敎我~~~ >____<"
感激不盡~~

回答 (2)

2009-04-02 8:33 pm
✔ 最佳答案
#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");
}
2009-04-02 6:40 pm
If you want to use these routines, GNU MP library has them. They come with source so you can look into how this is done.

http://gmplib.org/


收錄日期: 2021-04-30 12:54:19
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090402000010KK00774

檢視 Wayback Machine 備份