运行结果:
Enter the first of 19 or fewer digits number: 8837899188361066012
Enter the second of 19 or fewer digits number: 6832629488379649259
Integer overflow.
Enter the first of 19 or fewer digits number: 3789918836106601288
Enter the second of 19 or fewer digits number: 3262948837964925968
3789918836106601288 + 3262948837964925968 = 7052867674071527256
sum.cpp
#include <iostream>
using namespace std;
const int LEN = 19; // unsigned long 最高只能存储19位无符号数据,超过会导致溢出
int fillArray(char ar[]); // 从键盘获取小于等于19位数字,并存入char类型数组
unsigned long charToInteger(char ar[], int length); // char 类型转 int 类型
bool computeDigits(unsigned long n); // 计算两数相加的和的位数,超过19位返回true,否则返回false
/* 计算一个数的N次方,切记此处不可使用c++库函数 pow(double x, double n),
* 因为其返回值为 double 类型,而 double 类型并不能准确的存储一个整数,
* 使用此函数会导致 char 类型转换 int 数据出错。
*/
unsigned long power(unsigned long x, int count);
int main() {
char a[LEN];
char b[LEN];
cout << "Enter the first of 19 or fewer digits number: ";
int usedDigitsA = fillArray(a);
cin.ignore(); // 丢弃残留在输入流 cin 中的 '\n'
cout << "Enter the second of 19 or fewer digits number: ";
int usedDigitsB = fillArray(b);
unsigned long aL = charToInteger(a, usedDigitsA);
unsigned long bL = charToInteger(b, usedDigitsB);
unsigned long sum = aL + bL;
if (computeDigits(sum))
cout << "Integer overflow.";
else
cout << aL << " + " << bL << " = " << sum << "\n";
return 0;
}
int fillArray(char ar[]) {
int digits = 0;
char tmp;
for (int i = 0; i < LEN && ((tmp = cin.get()) != '\n'); i++) {
ar[i] = tmp;
digits++;
}
return digits;
}
unsigned long charToInteger(char ar[], int length) {
unsigned long n = 0;
int digits = length;
for (int i = 0; i < length; i++)
n += static_cast<unsigned long>(ar[i] - '0') * power(10, --digits);
return n;
}
bool computeDigits(unsigned long n) {
int count = 1;
while (n /= 10)
count++;
if (count > 19)
return true;
else
return false;
}
unsigned long power(unsigned long x, int count) {
unsigned long p = 1;
while (count--)
p *= x;
return p;
}