两个数特别大,相乘起来超过了long int型的范围?怎么计算?
比如:要计算123456789987654321 * 987654321123456的值,怎么写程序?
/* large_num_operation.cpp */
#include <iostream>
#include <cstring>
using namespace std;
void calc_result(string first, string second);
int main()
{
// 0. 定义并输入两个字符串
string first;
cout<<"Input number1:"<<endl;
cin>>first;
string second;
cout<<"Input number2:"<<endl;
cin>>second;
calc_result(first, second);
return 0;
}
void calc_result(string first, string second)
{
// 1. 记录两个字符串长度
int flen = first.size();
int slen = second.size();
int result[flen+slen]; // 定义数组存储每一位运算结果
// 2. 初始化数组
memset(result, 0, sizeof(result));
// 3. 相乘
for(int i=0; i<flen; i++)
{
for(int j=0; j<slen; j++)
{
result[i+j+1] += (first.at(i)-'0')*(second.at(j)-'0');
}
}
// 4. 进位
for(int i=flen+slen-1; i>=0; i--)
{
if(result[i] >= 10)
{
result[i-1] += result[i]/10;
result[i] = result[i]%10;
}
}
// 5. 输出
cout<<endl<<"The result: "<<endl;
int i=0;
while(result[i]==0){i++;}; // 若以0开头,去掉0
for(; i<flen+slen; i++)
{
cout<<result[i];
if ( i != (flen+slen-1) && (flen+slen-1-i)%3 == 0 )
cout<<",";
}
cout<<endl;
}