「java摇色子」java摇色子代码

博主:adminadmin 2022-11-26 07:54:07 72

本篇文章给大家谈谈java摇色子,以及java摇色子代码对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java投掷骰子,求点数的出现概率

很简单 。

int [] num = new int[3]; //数组长度为3

int diag=0; //统计出现5的次数

for(int i=0;i3;i++){ //掷骰子三次 ,也就是三个骰子

随机数字 num[i]=(int)(Math.random()*5)+1; //随机1-6的数字

if(num[i]==5){

diag++; //当骰子等于5的时候,统计次数加1;

}

}

double a=diag/3; //骰子出现5的次数,除以骰子总数,得到概率。

System.out.println(a);

java程序设计,投骰子,求概率

你这么写吧。抛一次骰子,就是你刚才那个,循环3次,取1-6随机数,取到5,然后youFive++;取不到5,meiFive++。你这样抛10000次,用youFive/10000就很接近真的概率了。 但这是统计的思路,样本可能存在偏差,不知道你算这个概率为什么编程?你计算出3个骰子都没有5的概率用1减一下就好了,应该是这个吧1-(5/6)*(5/6)*(5/6)

java怎么写出当骰子点数为6时,在掷一遍的代码

加一个判断就好了,比如这样写

public

void

Dice(){

Random

random

=

new

Random();

int

count

=

random.nextInt(6)

+

1;//这里的骰子点数用随机数生成一个[1,6]之间的整数

//这里写你的代码逻辑

if(count

==

6){

Dice();//再掷一次

}

//这里写你的代码逻辑

}

java中编程实现如下的骰子游戏:丢下两个骰子,若分值的总值为7点,则“赢”;否则“输”。

public class Test {

public static void main(String[] args){

DieGame dieGame = new DieGame();

if (dieGame.play()) {

System.out.println("你赢了!");

} else {

System.out.println("你输了!");

}

}

}

class Die {

private int faceValue;

public int getFaceValue() {

return faceValue;

}

public void setFaceValue(int faceValue) {

this.faceValue = faceValue;

}

public void roll() {

this.faceValue = (int) (Math.random() * 6 + 1);

}

}

class DieGame {

private Die die1 = new Die();

private Die die2 = new Die();

public boolean play() {

die1.roll();

System.out.println("第一次点数:" + die1.getFaceValue());

die2.roll();

System.out.println("第二次点数:" + die2.getFaceValue());

if (die1.getFaceValue() + die2.getFaceValue() == 7) {

return true;

} else {

return false;

}

}

}

写一个java程序,摇两个骰子,用random,直到两个值相等为止

不知道你说的是random类还是math.random,所以写了两个

1. Math.random

public class Test1 {

public static void main(String[] args) {

int a, b;

a = (int)(1+Math.random()*(6));

b = (int)(1+Math.random()*(6));

while (a != b) {

System.out.println("Not equal! a=" + a + ", b=" + b);

a = (int)(1+Math.random()*(6));

b = (int)(1+Math.random()*(6));

}

System.out.println("Equal! a=b=" + a);

}

}

2. random类

import java.util.Random;

public class Test2 {

public static void main(String[] args) {

int a, b;

Random ra = new Random();

a = ra.nextInt(6)+1;

b = ra.nextInt(6)+1;

while (a != b) {

System.out.println("Not equal! a=" + a + ", b=" + b);

a = ra.nextInt(6)+1;

b = ra.nextInt(6)+1;

}

System.out.println("Equal! a=b=" + a);

}

}

关于java摇色子和java摇色子代码的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-11-26,除非注明,否则均为首码项目网原创文章,转载请注明出处。