Простая монетка Java Программа - PullRequest
2 голосов
/ 01 апреля 2020

Я использую класс случайных чисел и прошу его сложить общее количество голов / количество сальто .... но это не работает.

Любые подсказки будут полезны.

import java.util.Random;
public class FlipaCoin
{
    public static void main(String [] args)
    {
        Random rand= new Random();
        boolean a;
        while (a=true)
        {
            int flip=rand.nextInt(2);
            int heads=0;
            if (flip==1)
            {
                heads++;
            }
            double count=0;
            double percentage=heads/count;
            System.out.println(percentage);
            count++;
            if (percentage==50.0)
            {
                break;
            }
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 01 апреля 2020

См. Комментарии:

import java.util.Random;
public class FlipaCoin
{
    public static void main(String [] args)
    {
        Random rand= new Random();
        int heads=0; //you don't want to reset heads in every loop
        double count=0; //you don't want to reset heads in every loop
        //boolean a; //not needed
        while (true)
        {
            int flip=rand.nextInt(2);
            //int heads=0;
            if (flip==1)
            {
                heads++;
            }
            count++;
            double percentage= heads/count*100 ;// heads/count give fraction, not percentage 
            if (percentage==50.0)
            {
                System.out.println(percentage + "achived after "+ count +" flips");
                break;
            }
        }
    }
}

Вы также можете использовать rand.nextBoolean():

public static void main(String [] args)
{
    Random rand= new Random();
    int heads=0;
    double count=0;
    while (true)
    {
        boolean flip=rand.nextBoolean(); // true half the
        if (flip)
        {
            heads++;
        }
        count++;
        double percentage= heads/count*100;
        if (percentage==50.0)
        {
            System.out.println(percentage + "achived after "+ count +" flips");
            break;
        }
    }
}

Краткая версия:

public static void main(String [] args)
{
        Random rand= new Random();
        int heads=0, count=0;
        do
        {
            heads = rand.nextBoolean() ? heads+1 : heads;
            count++;
        }while((double)heads+100/count!= 50);
        System.out.println("50% achived after "+ count +" flips");
}
0 голосов
/ 01 апреля 2020

Я просмотрел вашу программу и пересмотрел ее, оставив свои отзывы в комментариях в тех местах, где они актуальны. Я надеюсь, что этот обзор поможет!

import java.util.*;

public class FlipaCoin {
  public static void main(String[] args) {
    Random rand = new Random();
    // don't
    // - boolean a;
    // If you're going to test a variable,
    // assign it a default value first
    boolean a = true;

    // Declaring these outside of the `while` loop below allows
    // them to exist through multiple executions of the loop's body
    int heads = 0;
    int count = 0;
    double percentage = 0;

    // It turns out that `percentage == 50.0` never evaluated to `true`, ever
    // Better to pick a limit beyond which
    int samples = 5000;

    // don't - while (a=true) {
    // Using the `=` operator assigns a value to a variable,
    // and this assignment itself results in a true, and loop forever
    // Using the `==` operator compares two operands for equality
    // of values, and returns true if same, false if different
    // This is how to test `a`.
    // while (a == true) {

    // We don't want it to loop forever though, so the condition was revised
    // `<=` is a "less than or equal to" comparison operator
    while (count <= samples) {
      int flip = rand.nextInt(2);
      // don't do this inside the loop
      // - int heads = 0;
      if (flip == 1) {
        heads++;
      }
      // don't do these inside the loop
      // - double count = 0;
      // - double percentage = heads / count;
      // Assigning a new value to a variable defined
      // outside the loop is what you want;

      // `(double) count` says "think of this value as a double" in just this line
      // but `count` stays int, so when logging below, it doesn't show as `105.00`
      percentage = heads / (double) count;

      // don't - System.out.println(percentage);
      // Give a little more context for what you're logging! :)
      System.out.println("Sample: " + count + "; Percent: " + percentage);

      count++;

      // don't, this will never succeed
      // - if (percentage == 50.0) {
      // -   break;
      // - }
    }
  }
}
...