用c++计算1234567890123456789012+12的值
时间: 2024-05-09 14:15:20 浏览: 14
由于这两个数都超出了C++中int或long long的表示范围,我们需要使用高精度计算来求解。以下是一种可能的实现:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
const int BASE = 1000000000; // 基数为10^9
typedef vector<int> BigInt;
void parseBigInt(const string& s, BigInt& num) {
for (int i = s.size() - 1; i >= 0; i -= 9) { // 每9位一组,转换为int存储
int x = 0;
for (int j = max(0, i - 8); j <= i; j++) {
x = x * 10 + (s[j] - '0');
}
num.push_back(x);
}
while (num.size() > 1 && num.back() == 0) num.pop_back(); // 去除前导0
}
void printBigInt(const BigInt& num) {
printf("%d", num.empty() ? 0 : num.back());
for (int i = num.size() - 2; i >= 0; i--) {
printf("%09d", num[i]); // 不足9位前面补0
}
printf("\n");
}
BigInt operator+(const BigInt& a, const BigInt& b) {
BigInt c;
int carry = 0;
for (int i = 0; i < a.size() || i < b.size() || carry; i++) {
if (i < a.size()) carry += a[i];
if (i < b.size()) carry += b[i];
c.push_back(carry % BASE);
carry /= BASE;
}
return c;
}
int main() {
string s1 = "1234567890123456789012";
string s2 = "12";
BigInt a, b;
parseBigInt(s1, a);
parseBigInt(s2, b);
BigInt c = a + b;
printBigInt(c);
return 0;
}
```
输出结果为:
```
1234567890123456789024
```