C++大整数加减法
简单实现了加减法,以后有时间了完善乘除法。
/* * * 大整数加减法 * */ #include <iostream> #include <string> #include <stdlib.h> using namespace std; #define N 200 //反转字符串 string res(string s) { int i = 0; int j = s.length() - 1; while (i < j) { swap(s[i], s[j]); i++; j--; } return s; } //转换字符串为int数组 int pub(string s1, string s2, int a[], int b[]) { s1 = res(s1); s2 = res(s2); int len1 = s1.length(); int len2 = s2.length(); int i, maxlen; maxlen = (len1 > len2) ? len1 : len2; for (i = 0; i < len1; i++) { a[i] = s1[i] - '0'; } for (i = 0; i < len2; i++) { b[i] = s2[i] - '0'; } return maxlen; } //加法运算 void add(string s1, string s2) { int a[N] = {0}, b[N] = {0}, c[N] = {0}; int i, maxlen; maxlen = pub(s1, s2, a, b); for (i = 0; i < maxlen; i++) { c[i] = a[i] + b[i]; } for (i = 0; i < maxlen; i++) { if (c[i] >= 10) { c[i] = c[i] - 10; c[i + 1]++; if (maxlen - 1 == i) { maxlen++; } } } for (i = maxlen - 1; i >= 0; i--) { cout << c[i]; } cout << endl; } //减法运算 void sub(string s1, string s2) { int a[N] = {0}, b[N] = {0}, c[N] = {0}; int i, maxlen, resultlen = -1; bool aSmall = false; //两数相等直接输出0 if (s1.compare(s2) == 0) { cout << 0 << endl; return; } int len1 = s1.length(); int len2 = s2.length(); if (len1 == len2) { aSmall = s1 < s2; } else { aSmall = len1 < len2; } maxlen = pub(s1, s2, a, b); if (aSmall) { cout << '-'; for (i = 0; i < maxlen; i++) { c[i] = b[i] - a[i]; } } else { for (i = 0; i < maxlen; i++) { c[i] = a[i] - b[i]; } } for (i = 0; i < maxlen; i++) { if (c[i] < 0) { c[i] = c[i] + 10; c[i + 1]--; if (maxlen - 1 == i) { maxlen++; } } } ///////////////////////// //去掉结果前的0 for (i = maxlen; i > 0; i--) { if (c[i] != 0) break; else if (c[i] == 0) { resultlen = i - 1; } } if (resultlen > 0) { maxlen = resultlen; } else { maxlen = 0; } //////////////////////// for (i = maxlen; i >= 0; i--) { cout << c[i]; } cout << endl; } int main() { string s1, s2; char ch; do { cout << "输入2个正整数:\n"; cin >> s1 >> s2; if (!isdigit(s1[0]) || !isdigit(s2[0])) break; cout << "\n输入操作符(+或者-):"; cin >> ch; switch (ch) { case '+': add(s1, s2); break; case '-': sub(s1, s2); break; } cout << endl; } while (true); system("pause"); return 0; }