我有一些問題,整理一個隨機雙只有一個小數點。我已經在網上看了一下,從我能說的和理解的角度看,我已經掌握了一切。然而,顯然不是。具體來說,似乎我可能會錯誤地使用'round()',因爲即使我沒有對其進行所有其他乘法(等等),它也不會繞過double。C++舍入隨機雙
double u;
srand(unsigned(time(NULL)));
for(int i = 0; i < 10; i++){
u = (double)rand()/(RAND_MAX+1) + (rand()%101); //Acquire random number, turn it into decimal and then add it to another number between 0-100.
u *= 10; //Shift numbers left to remove first decimal from round.
round(u); //Round to nearest whole number.
u /= 10; //Shift right to return the first decimal.
cout<<u<<" "<<flush;
}
這種方法對我來說似乎很糟糕。很明顯,它不會在雙倍的更高級別上運行(因爲* 10可能會超載它,或者不管它叫什麼)。我希望有人能夠:
A.讓我看看我的代碼出錯了,或者提示它。 B.建議一個更好,更有效的方法來做到這一點。我確定肯定有一個。 C.讓我看看除了第一位以外的小數點。
並提前非常感謝!
http://stackoverflow.com/questions/11208971/round-a-float-to-a-given-precision – RhinoDevel
你想要什麼範圍內的隨機數? – Bathsheba
您的代碼沒有進行輪換,因爲您沒有對四捨五入值進行任何操作 - 「round」不修改其參數,它會返回結果。 – molbdnilo