小数精确相乘

27 篇文章 0 订阅
#include <iostream>
#include <cassert>
using namespace std;

void PrintMulNum(char *numA,int alen,char *numB,int blen)
{
	if (NULL == numA || NULL == numB || alen <=0 || blen <=0)
	{
		return;
	}
	int *num1 = new int[alen-1];//减去小数点1位
	assert(num1 != NULL);

	int *num2 = new int[blen-1];
	assert(num2!=NULL);

	int *result = new int[(alen-1)*(blen-1)+1];
	assert(result != NULL);
	memset(result,0,((alen-1)*(blen-1)+1)*sizeof(int));

	int i,j,pointCountA=0,pointCountB=0,posA,posB;
	for (i=0,j=0; j < alen;j++)
	{
		if (numA[alen-1-j]!='.')
		{
			pointCountA++;
			num1[i]=numA[alen-1-j]-'0';
			cout << "---"<<i<<"---"<<num1[i]<<endl;

			i++;
		}
		else
		{
			posA = pointCountA;//计算小数点位置
		}

	}

	for (i=0,j=0; j < blen;j++)
	{
		if (numB[blen-1-j]!='.')
		{
			pointCountB++;
			num2[i]=numB[blen-1-j]-'0';
			cout << "---"<<i<<"---"<<num2[i]<<endl;

			i++;

		}
		else
		{
			posB = pointCountB;
		}

	}

	int point = posA+posB;//计算result中小数点位置

	for (i=0; i < alen-1; ++i)
	{
		for (j=0;j<blen-1;++j)
		{
			result[i+j] +=num1[i]*num2[j];
			cout << "---"<<i+j<<"---"<<result[i+j]<<endl;

		}
	}

	for (i=0;i < (alen-1)*(blen-1);i++)
	{
		if (result[i] > 9)
		{
			result[i+1] += result[i]/10;
			result[i] %=10; 
			
		}
		cout << "---"<<i<<"---"<<result[i]<<endl;

	}
	bool flag = true;
	for (i=(alen-1)*(blen-1);i>=0;--i)
	{
		if (result[i]==0&&flag)
		{
			continue;
		}
		else
		{
			if (i ==point)
			{
				cout <<result[i]<<".";
			}
			else
				cout << result[i];
			flag=false;
		}
	}

	delete[] num1;
	delete[] num2;
	delete[] result;

	return;

}

int main()
{
	char *n="1.243";
	char *m="3.241555";
	PrintMulNum(n,strlen(n),m,strlen(m));
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值