2016-01-29 54 views
-2

這是此頁面上回答的跟進問題:C++:高精度隨機雙號

How to generate random double numbers with high precision in C++?

#include <iostream> 
#include <random> 
#include <iomanip>  

int main() 
{ 
    std::random_device rd; 

    std::mt19937 e2(rd()); 

    std::uniform_real_distribution<> dist(1, 10); 

    for(int i = 0 ; i < 10; ++i) 
    { 
     std::cout << std::fixed << std::setprecision(10) << dist(e2) << std::endl ; 
    } 

    return 0 ; 
} 

答案工作正常,但我有一個很難認識到如何把這個代碼的輸出在一個雙變量中,而不是打印到stdout。有人能幫忙嗎?

謝謝。

+3

你嘗試'some_variable = DIST(E2);'? – NathanOliver

+0

如果我只是運行「double var = dist(e2);」它只是給出6位數字...... –

+1

然後,你應該在問題中顯示。現在不清楚你在問什麼。 – NathanOliver

回答

3

你得到實際精度和之間的混淆顯示精度 - 試試這個:

#include <iostream> 
#include <random> 
#include <iomanip>  

int main() 
{ 
    std::random_device rd; 
    std::mt19937 e2(rd()); 
    std::uniform_real_distribution<> dist(1, 10); 

    double v = dist(e2); // get a random double at full precision 

    std::cout << std::fixed << std::setprecision(10) << v << std::endl; 
          // display random double with 10 digits of precision 
    return 0; 
} 
+0

是的,我有點困惑,認爲變量包含的內容取決於setprecision函數。謝謝 –

+2

沒問題 - 這是混淆的常見來源。 –

+0

@PaulR我也有類似的問題[這裏](http://stackoverflow.com/questions/35258164/how-to-prevent-numbers-from-showing-up-in-scientific-notations)。如果可能的話,你能幫我一把。 – user1950349