两个值不会产生他们应该

时间:2016-04-27 10:52:55

标签: java

我目前正在为学校做作业,我需要创建一个程序,使用Math.random()来获取随机值,并根据值,输出" Heads"或" Tails"。它需要这样做10次。然后,它需要找到程序输出结束的次数百分比,以及输出尾数的百分比。但是,它无法正常工作。它总是输出头/尾是0%的投掷。有人可以解释一下原因吗?

public class HeadsTails
{
    public static void main(String[] args)
    {
        int v;
        double i;

        int heads = 0, tails = 0;

        double headsPercent, tailsPercent;

        for(v = 1; v <= 10; ++v)
        {
            i = Math.random();
            if(i <= 0.5)
            {
                System.out.println("Heads");
                heads = heads + 1;
            }
            else if(i > 0.5)
            {
                System.out.println("Tails");
                tails = tails + 1;
            }
        }
        headsPercent = (heads / 10) * 100;
        tailsPercent = (tails / 10) * 100;
        System.out.println("Heads were " + headsPercent + "% of the tosses.");
        System.out.println("Tails were " + tailsPercent + "% of the tosses.");
    }
}

除了那些只是让程序正常运行的东西之外,我也对可以进行的任何改进持开放态度。

1 个答案:

答案 0 :(得分:1)

问题是整数数学。 headstails都是int,所以:

heads / 10

...会产生int结果,在您的情况下几乎总是0,因为在int - land,1 / 102 / 10,通过{{1都是9 / 10。只有当所有的卷都是头部或者所有卷都是尾巴时,0 10 / 10才是1

在进行数学运算之前转换为double

headsPercent = ((double)heads / 10) * 100;
tailsPercent = ((double)tails / 10) * 100;

执行fixes the problem

附注1:您可以使用+=添加变量,例如:

heads += x;

当然,当您添加的内容为1时,您可以使用增量运算符,前缀为:

++heads;

或后缀

heads++;

(就更新headstails而言,哪个更重要。)

附注2:您不需要else if (i > 0.5)。如果您考虑逻辑,那么if (i <= 0.5) ... else ...这意味着i一旦到达> 0.5else肯定是if (i > 0.5),不需要i一部分。

如果你这样做,你甚至不再需要for(v = 1; v <= 10; ++v) { if(Math.random() <= 0.5) { System.out.println("Heads"); ++heads; } else { System.out.println("Tails"); ++tails; } }

String QUERY_URL = "https://api.immotoolbox.com/xml/2.0/MCRE/produits/?search[typeTransaction]=Vente&_locale=fr";