Java 15抛硬币生成器仅0生效1从未命中 Math.random问题排查
问题原因
Math.random() 返回的是*[0.0, 1.0)*左闭右开区间的双精度浮点数,你代码中写的(int) (Math.random()*1)计算后数值范围仍为[0.0,1.0),强制转换为int时会截断小数部分,最终结果永远为0,不可能生成1,并非概率巧合,属于代码逻辑错误。
修复方法
- 将随机数生成逻辑改为
int coin = (int) (Math.random() * 2);即可,修改后数值范围为[0.0,2.0),强转int后只会得到0或1两个结果,符合抛硬币50%概率的需求。
修正后完整代码
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()*2); 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"); } } }
内容的提问来源于stack exchange,提问作者Duoinvasion
相关产品推荐
相关产品推荐

