深入分析C++中两个大数相乘结果不正确的问题
深入分析C++中两个大数相乘结果不正确的问题
发布时间:2016-12-28 来源:查字典编辑
摘要:在编写代码做测试时发现两个大数相乘结果不正确的问题,测试代码如下:#include"stdafx.h"#include#includeint...

在编写代码做测试时发现两个大数相乘结果不正确的问题,测试代码如下:

#include "stdafx.h"

#include<stdlib.h>

#include<time.h>

int _tmain(int argc, _TCHAR* argv[])

{

time_t temp1=1345172428000000;

time_t temp2=1345172428*1000000;

::system("pause");

return 0;

}

经过测试发现temp1与temp2并不相等。

但是修改为如下代码:

#include "stdafx.h"

#include<stdlib.h>

#include<time.h>

int _tmain(int argc, _TCHAR* argv[])

{

time_t temp1=1345172428000000;

time_t temp3=1345172428;

time_t temp4=1000000;

time_t temp2=temp3*temp4;

::system("pause");

return 0;

}

经过测试发现temp1与temp2并相等。

分析原因:

1345172428和1000000都是当做int型来处理的,他们相乘的结果也是当做int型,只是乘积会被强制转换成time_t,但是在求乘积的时候就已经溢出了,所以在转换成time_t也是错的。

结论:

在大数乘法时需要考虑乘积溢出问题。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C语言学习
热门C语言学习
编程开发子分类