【问题标题】:50 tries and 1 hasnt been the answer at all [duplicate]50次尝试,1次根本不是答案[重复]
【发布时间】:2021-09-04 03:01:35
【问题描述】:

这是用 Java 15.0.2 和 netbeans 12.0LTS 编码的 我想假设我正确地编码了这个硬币翻转发生器,但 0 是唯一给我正确的选项,1 从来没有。我不知道是我把 Math.random 搞砸了,还是我就是这么倒霉。

package pkgthis.thing;

import java.util.Scanner;
/**
 *
 * @author Student
 */
public class LabQuestion6 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int coin = (int) (Math.random()*1);

        int choice;

        Scanner keyboard = new Scanner(System.in);
        
        System.out.println("Please choose 1 or 0: \n");

        choice = keyboard.nextInt();
        
        if (choice == coin) 
        {
            System.out.println("You are correct");  
        } 

        else 
        {
            System.out.println("You are incorrect");
        }
    }
    
}

【问题讨论】:

  • 先阅读Math.random()的文档。然后尝试打印一些值System.out.println(Math.random()); 以了解该方法的工作原理。
  • int coin = (int) (Math.random()*1);; Math.random() 将是 0 和 1 之间的某个值,然后将其乘以 1。这是同一件事,所以它仍然是 0 和 1 之间的某个值。然后将其转换为 int。在java中从浮点数(小数)到整数(不是小数)总是向0舍入,这称为截断。所以这个数字永远是0。你的错误就在这条线上。
  • [1] nextInt(bound) method of Random 是比使用 Math.random() 更好的方法。 [2] 另外,请注意 NetBeans 12.0 不支持使用 Java 15。From the 12.0 release notes:“Apache NetBeans 12.0 在 JDK LTS 版本 8 和 11 以及 JDK 14 上运行,即,此 NetBeans 发布时的当前 JDK 版本。"

标签: java random netbeans


【解决方案1】:

Math.random 总是给出一个大于或等于 0 且小于 1(不包括)的数字。将其转换为 int 将始终为您提供 0。您的方法的替代方法可能是:

int coin = (int) (Math.random()*2);

【讨论】:

  • nextInt(0, 2)
  • 这个问题在 SO 上已经出现过好几次了。请在发布答案之前检查重复项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 2019-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多