[英]Trouble generating random numbers?
rndmBid=rand() % (sellPtr->sellPrice + (1.25*sellPtr->startPrice));
這條線怎么了? 除1.25
(顯然)外,所有內容均為整數,並且編譯器給出錯誤,指出invalid operands of types 'int' and 'double' to binary 'operator%'.
我嘗試將startPrice
和rndmBid
更改為兩倍,但是沒有運氣。 有什么建議么?
將double
精度數引入算術表達式后,所有內容都會被提升/轉換為雙精度數。 因此,您需要轉換回整數:
rndmBid = rand() % static_cast<int>( ... );
(我相信您意識到您的隨機數不會均勻分布。)
rhs返回一個雙精度數,而%
僅適用於整數。 將結果轉換為整數:
rand() % static_cast<int>(sellPtr->sellPrice + (1.25 * sellPtr->startPrice));
(sellPtr->sellPrice + (1.25*sellPtr->startPrice)
是雙(sellPtr->sellPrice + (1.25*sellPtr->startPrice)
因為(1.25*sellPtr->startPrice)
是雙(1.25*sellPtr->startPrice)
因為1.25
是雙(1.25*sellPtr->startPrice)
。將結果轉換為int並將編譯:
rndmBid=rand() % static_cast<int>(sellPtr->sellPrice + (1.25*sellPtr->startPrice));
您將int添加到double中,因此結果是double,不能與%
運算符一起使用。
要解決此問題,您需要執行以下操作:
rndmBid=rand() % ((int)(sellPtr->sellPrice + (1.25*sellPtr->startPrice)));
只要雙精度數不大於整數中的整數就可以使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.