<c++>两个特别大的数之间相乘怎么计算?

两个数特别大,相乘起来超过了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;
}


结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值