math.random 总是给出 0 结果 [英] math.random always give 0 result

查看:46
本文介绍了math.random 总是给出 0 结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ubuntu 14.04.3 LTS,我正在从书中学习 Java.我尝试使用 Ubuntu Terminal 来遵循书中的一个示例,并且我正在使用 Sublime Text.这是代码

I am using Ubuntu 14.04.3 LTS and I am studying Java from the book. I tried to follow one example on the book with Ubuntu Terminal and I'm using Sublime Text. Here is the code

import java.util.Scanner;

public class RepeatAdditionQuiz{
    public static void main(String[] args){
        int number1 = (int)(Math.random()%10);
        int number2 = (int)(Math.random()%10);

        Scanner input = new Scanner(System.in);

        System.out.print(
            "What is "+number1+" + "+number2+"?");
        int answer = input.nextInt();

        while(number1+number2 != answer){
            System.out.print("Wrong answer. Try again. What is "
                 +number1+" + "+number2+"? ");
            answer = input.nextInt();
        }
        System.out.println("You got it!");
    }
}

但问题是,当我编译并执行它时.它给了我结果

But the problem is, when I compiled it and executed it. It gives me result

什么是 0 + 0?_

what is 0 + 0?_

每次.它假设给我随机数,是的,它可以是 0.但我尝试运行它超过 10 次,当它假设从 0-9 随机时,它一直给我 0 + 0.

every time. It suppose to give me random number, and yes, it can be 0. But I tried to run it more than 10 times, it keeps giving me 0 + 0, when it's suppose to random from 0-9.

当我输入 0 作为结果时,0 + 0 的结果很好,它让我摆脱了循环

The result of 0 + 0 is fine when I typed 0 as a result, it gets me out of the loop

我是否错过了一些使数学库正常工作的东西?如何解决随机化问题?

Did I miss something to make the math library works? How can I fix the randomize issue?

推荐答案

Math.random() 返回一个介于 0(含)和 1(不含)之间的双精度值.它不返回整数值.因此,当您对 Math.random() 取模 10 生成的数字时,它返回相同的双精度值.最终转换为 int 使该值始终为 0.

Math.random() returns a double value between 0 (inclusive) and 1 (exclusive). It does not return an integer value. Therefore, when you take the number produced by Math.random() modulo 10, it returns the same double value. The final cast to int makes that value always 0.

运行以下代码亲自查看:

Run the following code to see for yourself:

double random = Math.random();
System.out.println(random); // for example 0.5486395326203879
System.out.println(random % 10); // still 0.5486395326203879
System.out.println((int) (random % 10)); // outputs 0

您真正想要的是使用 Random 对象并使用 Random.nextInt(bound).要获得 0 到 9 之间的随机整数,您可以使用:

What you really want is to use a Random object and use Random.nextInt(bound). To have a random integer between 0 and 9, you can use:

Random random = new Random();
int value = random.nextInt(10);

这篇关于math.random 总是给出 0 结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆