计算长整型的总和

Calculation the sum of long long int

本文关键字:长整型 计算      更新时间:2023-10-16

(计算长长数之和)

每当我输入一个长长的数字时,程序总是返回 -1 或 -2,有人知道为什么吗?

#include <iostream>
#include <math.h>
#include <string>
#include<iomanip>
using namespace std;
int main()
{
int n,i;
long long x1,x2,s;
do{
cin>>n;
}while(n<1);
long long t1[n];
long long t2[n];
string ch1,ch2;
i=0;
do{
    do{
        scanf("%lld %lld", &x1, &x2);   
        ch1=to_string(x1);
        ch2=to_string(x2);
    }while((ch1.length()>pow(10,5)) || (ch2.length()>pow(10,5)));
t1[i]=x1;
t2[i]=x2;
i++;
}while(i<n);
for(i=0;i<n;i++){
    s=t1[i]+t2[i];
    cout<<s<<endl;
}
return 0;
}

找不到解决方案,请帮忙! 提前感谢!

示例输入:

1

14444444444444444111115556

55656464684646464646647676

输出

-阿拉伯数字

//编辑:

有没有办法计算100000:)的总和十进制数字,如使用标准库的示例中的数字?

基本积分类型(如 long long)可以表示的范围有限。如果计算导致的结果大于可以表示的结果,它将溢出。有符号整数溢出在C++中具有未定义的行为。

通过使用整数数组来表示数字的不同部分,可以表示无限范围的数字(理论上,内存限制了实践)。这种技术称为任意精度算术

C++标准库中没有任意精度类型的实现,因此要么必须自己实现一个,也可以使用其他人实现的库。