2015-08-25 24 views
1

我完全不知道該如何實際完成這個任務,我主要設法讓我的代碼工作,直到我嘗試在cpp_dec_float上運行ceil()< >在這種情況下,我會仔細檢查boost文檔和谷歌搜索,然後拒絕合作。我已經得出結論,我無法自己找到答案,於是我轉而尋求無限可勝的程序員的幫助。加速,在任意精度浮點數和整數類型之間進行轉換

#include <iostream> 
#include <boost/multiprecision/cpp_int.hpp> 
#include <boost/multiprecision/cpp_dec_float.hpp> 
#include <boost/math/special_functions/pow.hpp> 
#include <boost/chrono/ceil.hpp> 
#include <boost/multiprecision/number.hpp> 

namespace mp = boost::multiprecision; 
using namespace std; 
using namespace boost::math; 
using namespace boost::chrono; 
using Int = mp::cpp_int; 
Int reward(Int baseReward, int percent); 

int main(int argc, char** argv) 
{ 

    reward = calcReward(immBase, percent); 
    return 0; 
} 

Int calcReward(Int baseReward, int percent) 
{ 
    using Dec = mp::number<mp::cpp_dec_float<0>>; 
    Dec mult = 0.1+0.01*percent; 
    Dec five = 5; 
    Dec base = baseReward.convert_to<Dec>(); 
    Int result = ceil(five*base*mult); 

    return result; 
} 

這是從不必要的垃圾剝離時的代碼,這五個變量是一個骯髒的黑客得到它接受任意精度浮點值的乘積(因爲它剛剛決定說,沒有匹配的操作*除此以外)。 這是相當困惑和相當令人沮喪,ceil()。convert_to()也不工作,並吐出一個任意不可解讀的錯誤。 (模板錯誤無法讀取)

此代碼在編譯時確實需要-std = C++ 11標誌,這可能很明顯。

+0

https://www.livecoding.tv/sehe/ – sehe

+1

如果你喜歡使用不合格在廚房偷看:https://www.livecoding.tv/video/boost-multiprecision-et-eval-and-conversions/([實驗](http://chat.stackoverflow.com/transcript/10?m = 24182469#24182469)) – sehe

回答

2

通常的罪魁禍首是BMP表達式的結果不是它們的目標類型,但仍然是「懶惰」的表達式模板,並且它們沒有所有的隱式轉換。所以,你需要將這些 「人工」 評估(明確):

return Dec(ceil(five*base*mult)).convert_to<Int>(); 

看到它Live On Coliru

#include <iostream> 
#include <boost/multiprecision/detail/default_ops.hpp> 
#include <boost/multiprecision/cpp_int.hpp> 
#include <boost/multiprecision/cpp_dec_float.hpp> 
#include <boost/math/special_functions/pow.hpp> 
#include <boost/multiprecision/number.hpp> 

namespace mp = boost::multiprecision; 

using Int = mp::cpp_int; 

Int calcReward(Int baseReward, int percent); 

int main() 
{ 
    Int const immBase = 400; 
    int const percent = 12; 

    std::cout << calcReward(immBase, percent); 
} 

Int calcReward(Int baseReward, int percent) 
{ 
    using Dec = mp::cpp_dec_float_50; 
    Dec mult = 0.1+0.01*percent; 
    Dec five = 5; 
    Dec base = baseReward.convert_to<Dec>(); 

    return Dec(ceil(five*base*mult)).convert_to<Int>(); 
} 

注:

+0

禁用表達式模板有什麼潛在的缺點?速度並不是什麼大問題,只是爲我計算一個奇異方程,而不管這兩個解決方案看起來是否夠簡單。 – LordHexahedron

+0

好吧,所以我無法使表達式模板選項工作(儘管我沒有很努力),但是您推薦的解決方案確實有效,非常感謝您的幫助。 – LordHexahedron

+0

但是我注意到一些特別感興趣的東西,當輸入大數字(150左右)時,它會拋出what():解析字符串時發現意外的內容。這意味着提升並不是對非常大數量的浮點的積分。 (即使它是任意的精確數字) – LordHexahedron