[英]C++ Addition Not Working
我寫了一個解決Google Code Jam問題的解決方案,如下所示:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <cmath>
using namespace std;
int main(int argc, char** argv) {
ifstream in;
in.open(argv[1]);
int t, c = 0;
in >> t;
while(c++<t) {
string msg;
in >> msg;
map<char,int> m;
int base = 0;
for(char& ch : msg) {
if(!m[ch]) {
base++;
m[ch] = base == 1 ? base : (base == 2 ? -1 : base - 1);
}
}
if(base < 2)
base = 2;
double total = 0;
double p = pow(base, msg.size()-1);
for(char& ch : msg) {
if(m[ch] != -1) {
if(c == 37) cout << "total=" << total << "+" << (m[ch] * p) << "=" << total + (m[ch] * p) << endl;
total = total + (m[ch] * p);
}
p /= base;
}
cout.precision(0);
cout << fixed << "Case #" << c << ": " << total << endl;
}
in.close();
return 0;
}
如您所見,我在案例37中打印了一些調試語句,因為那里發生了一些奇怪的事情:
Case #36: 1000000000000000000
total=0+450283905890997376=450283905890997376
total=450283905890997376+100063090197999424=550346996088996800
total=550346996088996800+16677181699666570=567024177788663360
total=567024177788663360+5559060566555523=572583238355218880
total=572583238355218880+1853020188851841=574436258544070720
total=574436258544070720+1235346792567894=575671605336638592
total=575671605336638592+205891132094649=575877496468733248
total=575877496468733248+68630377364883=575946126846098112
total=575946126846098112+22876792454961=575969003638553088
total=575969003638553088+15251194969974=575984254833523072
total=575984254833523072+847288609443=575985102122132544
total=575985102122132544+564859072962=575985666981205504
total=575985666981205504+62762119218=575985729743324736
total=575985729743324736+20920706406=575985750664031168
total=575985750664031168+6973568802=575985757637600000
total=575985757637600000+129140163=575985757766740160
total=575985757766740160+28697814=575985757795437952
total=575985757795437952+1594323=575985757797032256
total=575985757797032256+177147=575985757797209408
total=575985757797209408+59049=575985757797268480
total=575985757797268480+6561=575985757797275072
total=575985757797275072+4374=575985757797279424
total=575985757797279424+729=575985757797280128
total=575985757797280128+81=575985757797280192
total=575985757797280192+2=575985757797280192
Case #37: 575985757797280192
如您所見,在某些時候加法不能正常工作(例如575985757797279424 + 729 = 575985757797280153而不是575985757797280128)
我對這種行為感到非常震驚,非常感謝任何可能的解釋。
您已達到所選浮點類型的精度極限。
如果您堅持要避免使用整數(即定點數),則需要使用任意精度的數值庫來達到最佳效果。 在繼續使用這些功能之前,您還應該閱讀《浮點指南》 。
但是,這里的數字都可以放入一個64位整數中。 為什么不只使用它並為自己省些麻煩呢?
Double具有3個成分:符號,指數,分數。 例如1.2345表示為12345 * 10power-4
盡管Double的大小很長,但它有一些位用於指數部分,因此精度小於long long的精度,這會使float的精度為7個十進制數字,而double的精度為16個十進制數字。在指定位數后精確
也看了
1. https://chortle.ccsu.edu/java5/Notes/chap11/ch11_2.html
2. http://codeforces.com/blog/entry/1521?#comment-28329 (關於C ++中的戰俘)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.