问题描述
在int x =(Math.random()* a)行下面的代码中,我收到一条错误,上面写着不兼容的类型:可能有损转换从double转换为int在* a);
In the code bellow on the line "int x = (Math.random() * a)" I get a error that says "incompatible types: possible lossy conversion from double to int" at "* a);"
`
import java.util.Scanner;
public class problem4 {
public static void rollDice() {
Scanner reader = new Scanner(System.in);
System.out.println("How many random numbers should be generated?");
int n = reader.nextInt();
Scanner reader1 = new Scanner(System.in);
System.out.println("What is the number of values for each random draw?");
int a = reader.nextInt();
for (int i = 0; i <= n; i++) {
int x = (Math.random()* a);
System.out.println("Random number "+i+" is "+x+".");
}}}`
我在BlueJ中使用Java。
I am using Java in BlueJ.
推荐答案
Math.random
返回 double
。然后尝试将该双倍乘以 a
并将其放入 int
。
Math.random
returns a double
. Then you try to multiply that double by a
and put it into an int
.
int
总是一个整数(没有小数位)。所以它通过执行该操作(将其放回 int
)告诉您正在丢失这些小数位。
An int
is always a whole number (no decimal places). So it's telling you that you're losing those decimal places by doing that operation (putting it back into an int
).
您可以通过使 x
a double
。或者,如果您确实需要整数,则可以通过执行以下操作将 x
的值显式转换为 int
:
int x =(int)(Math.random()* a)
You could fix the problem by making x
a double
. Or if you actually want the whole numbers, you can explicitly cast the value of x
to an int
by doing:int x = (int) (Math.random() * a)
这篇关于(Math.random()* a);可能有损转换从double到int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!