zl程序教程

您现在的位置是:首页 >  后端

当前栏目

深入分析C++中两个大数相乘结果不正确的问题

C++ 问题 正确 两个 结果 深入分析 大数 相乘
2023-06-13 09:14:54 时间
在编写代码做测试时发现两个大数相乘结果不正确的问题,测试代码如下:
#include"stdafx.h"
#include<stdlib.h>
#include<time.h>
int_tmain(intargc,_TCHAR*argv[])

   time_ttemp1=1345172428000000;
   time_ttemp2=1345172428*1000000;
  ::system("pause");
   return0;
}
经过测试发现temp1与temp2并不相等。
但是修改为如下代码:
#include"stdafx.h"
#include<stdlib.h>
#include<time.h>
int_tmain(intargc,_TCHAR*argv[])
{
   time_ttemp1=1345172428000000;
   time_ttemp3=1345172428;
   time_ttemp4=1000000;
   time_ttemp2=temp3*temp4;
   ::system("pause");
   return0;
}
经过测试发现temp1与temp2并相等。
分析原因:
   1345172428和1000000都是当做int型来处理的,他们相乘的结果也是当做int型,只是乘积会被强制转换成time_t,但是在求乘积的时候就已经溢出了,所以在转换成time_t也是错的。
结论:
   在大数乘法时需要考虑乘积溢出问题。