深入分析C++中兩個(gè)大數(shù)相乘結(jié)果不正確的問題
更新時(shí)間:2013年05月16日 11:36:44 作者:
本篇文章是對(duì)C++中兩個(gè)大數(shù)相乘結(jié)果不正確的問題進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
在編寫代碼做測(cè)試時(shí)發(fā)現(xiàn)兩個(gè)大數(shù)相乘結(jié)果不正確的問題,測(cè)試代碼如下:
#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;
}
經(jīng)過測(cè)試發(fā)現(xiàn)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;
}
經(jīng)過測(cè)試發(fā)現(xiàn)temp1與temp2并相等。
分析原因:
1345172428和1000000都是當(dāng)做int型來處理的,他們相乘的結(jié)果也是當(dāng)做int型,只是乘積會(huì)被強(qiáng)制轉(zhuǎn)換成time_t,但是在求乘積的時(shí)候就已經(jīng)溢出了,所以在轉(zhuǎn)換成time_t也是錯(cuò)的。
結(jié)論:
在大數(shù)乘法時(shí)需要考慮乘積溢出問題。
#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;
}
經(jīng)過測(cè)試發(fā)現(xiàn)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;
}
經(jīng)過測(cè)試發(fā)現(xiàn)temp1與temp2并相等。
分析原因:
1345172428和1000000都是當(dāng)做int型來處理的,他們相乘的結(jié)果也是當(dāng)做int型,只是乘積會(huì)被強(qiáng)制轉(zhuǎn)換成time_t,但是在求乘積的時(shí)候就已經(jīng)溢出了,所以在轉(zhuǎn)換成time_t也是錯(cuò)的。
結(jié)論:
在大數(shù)乘法時(shí)需要考慮乘積溢出問題。
相關(guān)文章
文件編譯時(shí)出現(xiàn)multiple definition of ''xxxxxx''的具體解決方法
以下是對(duì)文件編譯時(shí)出現(xiàn)multiple definition of 'xxxxxx'的解決方法進(jìn)行了詳細(xì)的分析介紹,如也遇到此問題的朋友們可以過來參考下2013-07-07C++ boost::asio編程-同步TCP詳解及實(shí)例代碼
這篇文章主要介紹了C++ boost::asio編程-同步TCP詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-11-11