(Math.random()* a);可能有损转换从double到int

时间:2017-09-05 01:01:45

标签: java int double

在线上的代码" int x =(Math.random()* a)"我收到一个错误,上面写着"不兼容的类型:可能有损转换从double到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。

2 个答案:

答案 0 :(得分:3)

Math.random返回double。然后,您尝试将该双倍乘以a并将其放入int

int始终是整数(无小数位)。所以它通过执行该操作(将其重新放回int)告诉您正在丢失这些小数位。

您可以通过x double来解决问题。或者,如果您确实需要整个数字,则可以通过以下操作明确地将x的值转换为intint x = (int) (Math.random() * a)

答案 1 :(得分:0)

改为使用

https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt()

Random r = new Random ();
for (int x = 0; x < 5; x ++) {
    System.out.println(r.nextInt());
}

System.out.println(r.nextInt(52)); to limit to a number