int Comproll1= (int) (Math.random()*6+1);
int Comproll2= (int) (Math.random()*6+1);
while (m==1)
{
{
if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
else if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
else
{
cr= Comproll1+Comproll2;
cp= cp+cr;
}
}
嘿大家好!以上是我的代碼 - 無論如何,無論如何,無論如何,總是會顯示第一個選項,即「計算機的一個擲骰子是1,它在一輪中失去了所有點...」。即使我改變陳述的順序,它仍然會這樣做。有人可以向我解釋爲什麼會發生這種情況嗎?謝謝!Math.random if語句錯誤
首先,'int Comproll1 =(int)(Math.random()* 6 + 1)'應該是5 + 1。如果隨機返回6呢?然後你將有一個7的骰子。 – 2014-10-11 23:22:47
@BoratSagdiyev'Math。random()'返回一個浮點數'<1',所以'Math.random()* 6 + 1'的返回值永遠不會高於'6.99 ...',因此如果轉換爲整數,則返回6。 – lexith 2014-10-11 23:25:08
@BoratSagdiyev事實並非如此。 'Math.random()'的結果保證<1,因此,'Math.random()* 6'將始終爲<6,並且'Math.random()* 6 + 1'將始終爲<7 。對'int'的轉換使得6成爲最大值。 – ApproachingDarknessFish 2014-10-11 23:25:29