我无法将双精度数转换为整数(Math.random)

huangapple go评论66阅读模式
英文:

I can't convert a double to an int (Math.random)

问题

int rando = (Math.random() * ((1-3) + 1)) + 1;
		System.out.println(rando + "\n");

尝试打印一个1到2之间的随机数,但只会让我打印双精度数。

英文:
int rando = (Math.random() * ((1-3) + 1)) + 1;
		System.out.println(rando + "\n");

Trying to print a random number 1-2, but it will only let me print double.

答案1

得分: 3

//(int) (Math.random() * (upper - lower)) + lower; 
//上限是排他性的,因此要获取1-2之间的值,上限应为3
int rando = (int) (Math.random() * (3 - 1)) + 1;
System.out.println(rando + "\n");
英文:
	//(int) (Math.random() * (upper - lower)) + lower; 
	//uppar Limit is exclusive hence to get value between 1-2 UL shoude be 3
	int rando = (int) (Math.random() * (3 - 1)) + 1;
    System.out.println(rando + "\n");		

答案2

得分: 0

你需要将 Math.random() * 2 的结果转换为 int,因为 Math.random() 返回一个 double 值,将 double 值与 int 值相加/相减/相乘/相除也会返回一个 double 值。将 Math.random() * 2 的结果转换为 int,将确保它只能是 01,然后你可以加上 1 来获得所需的 int 值。

另一种方法是使用 Random#nextInt,它不需要进行类型转换。

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        int rando = (int) (Math.random() * 2) + 1;
        System.out.println(rando);

        // 第二种方法
        Random random = new Random();
        int rand = random.nextInt(2) + 1;
        System.out.println(rand);
    }
}

从示例运行中输出:

2
1
英文:

You need to cast the result of Math.random() * 2 into int because Math.random() returns a double value and adding/subtracting/multiplying/dividing a double value with an int value also returns a double value. Casting the result of Math.random() * 2 into int, will ensure that it will be either 0 or 1 and then you can add 1 to it to get the desired int value.

Another way of doing it can be by using Random#nextInt which will not require casting.

import java.util.Random;

public class Main {
	public static void main(String[] args) {
		int rando = (int) (Math.random() * 2) + 1;
		System.out.println(rando);

		// Second method
		Random random = new Random();
		int rand = random.nextInt(2) + 1;
		System.out.println(rand);
	}
}

Output from a sample run:

2
1

答案3

得分: -1

首先,你的代码甚至无法达到打印行,会导致编译错误。为了回答你的问题,你需要在Java中进行所谓的“类型转换(typecasting)”。这是将一个数据类型的值转换为另一个数据类型的过程。

int rando = (int)((Math.random() * ((3-1) + 1));
英文:

Firstly, your code wouldn't even reach the print line giving you a compiler error. To answer your question, you need to do what is called typecasting in java. It is the process of converting the value of one data type to another.

int rando = (int)((Math.random() * ((3-1) + 1);

huangapple
  • 本文由 发表于 2020年10月24日 03:26:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64506173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定