方法:利用string儲存一個數字,然後利用加減法的規則進行運算。
加法:各數位對齊,然後進行加減,若相加大於’9’則進位。
減法:方法同加法,但是要處理被減數與減數的大小問題,所以需要多加一個判斷條件。
乘法:利用多項式的思想,例如
除法:暫無
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
string result;
// 比較兩個string類型數的大小
bool compare(string a, string b) {
if (a.size() < b.size()) {
return 1;
}
else if (a.size() == b.size()) {
if (a < b) {
return 1;
}
}
return 0;
}
// 加法
void add(string a, string b) {
if (a.size() < b.size()) swap(a, b);
result = "0" + a;// 前面的0進位用,如果沒有進位,後面會刪掉這個0
for (int i = 0; i < b.size(); i++) {
result.at(a.size() - i) += b.at(b.size() - 1 - i) - '0';
}
for (int i = result.size() - 1; i >= 0; i--) {
if (result.at(i) > '9') {
result.at(i) = result.at(i) - 10;
result.at(i - 1) += 1;
}
}
if (result.at(0) == '0')
result.erase(0, 1);
}
// 減法
void substract(string a, string b) {
if (a == b) {
result = "0";
}
else if (b.at(0) == '-') {
b.erase(0, 1);
add(a, b);
}
else {
bool fuhao = 0;
if (compare(a, b)) {
swap(a, b);
fuhao = 1;
}
result = "1" + a;
for (int i = 0; i < b.size(); i++) {
result.at(a.size() - i) = result.at(a.size() - i) - b.at(b.size() - 1 - i) + '0';
}
for (int i = result.size() - 1; i >= 1; i--) {
if (result.at(i) < '0') {
result.at(i) = result.at(i) + 10;
result.at(i - 1) -= 1;
}
}
result.erase(0, 1);
if (result[0] == '0') {
result.erase(0, result.find_first_not_of('0'));// 把多餘的0刪除
}
if (fuhao) {
swap(a, b);
result.insert(0, "-");// 負數前面要加個負號“-”
}
}
}
// 乘法
void mutiple(string a, string b) {
result = "";
string temp;// 用來計算
string result_ = a;
for (int i = b.size() - 1; i >= 0; i--) {
temp = result_;
for (int j = 0; j < temp.size(); j++) {
temp.at(j) = (temp.at(j) - '0') * (b.at(i) - '0'); // 記錄0到81而不是從'0'開始,因爲'81'的ascii碼爲129 > 128 會溢出
}
temp = "0" + temp;// 前面補一位用來進位
for (int j = temp.size() - 1; j >= 1; j--) {
if (temp.at(j) > 9) { // 大於9而不是'9'的理由同上
temp.at(j - 1) = temp.at(j - 1) + (temp.at(j)) / 10;
temp.at(j) = (temp.at(j)) % 10;
}
}
// 因爲result的數字是'0'到'9',所以要還原(此時不會有溢出問題)
for (int i = 1; i < temp.size(); i++) {
temp.at(i) += '0';
}
add(result, temp);
result_ += "0";// 原因看原理
}
if (result.at(0) == '0') result.erase(0, 1);
}
int main() {
string a, b;
cout << "please input num 1 and num2:\n";
cin >> a >> b;
int size = a.size() > b.size() ? a.size() : b.size();
add(a, b);
cout << " " << setw(size + 1) << a << endl;
cout << "+" << setw(size + 1) << b << endl;
for (int i = 0; i <= size + 1; i++) {
cout << "-";
}
cout << endl;
cout << " " << setw(size + 1) << result << endl;
cout << endl;
substract(a, b);
cout << " " << setw(size + 1) << a << endl;
cout << "-" << setw(size + 1) << b << endl;
for (int i = 0; i <= size + 1; i++) {
cout << "-";
}
cout << endl;
cout << " " << setw(size + 1) << result << endl;
cout << endl;
mutiple(a, b);
size = result.size();
cout << " " << setw(size + 1) << a << endl;
cout << "*" << setw(size + 1) << b << endl;
for (int i = 0; i <= size + 1; i++) {
cout << "-";
}
cout << endl;
cout << " " << setw(size + 1) << result << endl;
system("pause");
return 0;
}