C++ <字符串转int类型并求和>

运行结果:

 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值