在基于增量while循环确定百分比时由逻辑错误导致的输出错误

时间:2014-04-19 01:56:24

标签: java loops for-loop logic

我创建了一个简单的类来计算赢/输百分比并返回必要的连续胜利金额,以根据给定的胜利,损失值,从用户获得给定输入的所需赢/输百分比。和期望的赢/输。然而,在运行程序时,我注意到输出给出了一个非常大的数字,而不是应该是一个相对较小的数字(所需的胜利数)。我不确定我创造了什么错误,但我确定它与我的howManyToWinLoss()方法中的while循环有关,或者我可能犯了一些错误在测试者类的输出中。无论如何,它们都位于下方,我很感谢您的帮助:

public class WinLossCalculator
{
    private int win;
    private int loss;
    private int totalGames;
    private double desiredWinLoss;
    private double winLoss;
    private int gamesToDWL;

    public WinLossCalculator(int w, int l, double dwl)
    {
        win = w;
        loss = l;
        totalGames = w + l;
        desiredWinLoss = dwl;
    }

    public double winPercent()
    {
        return winLoss = (double)win/(double)totalGames;
    }

    public double lossPercent()
    {
        return (double)loss/(double)totalGames;
    }

    public int howManyToWinloss()
    {
        int x = 0;
        while(winLoss < desiredWinLoss)
        {
            winLoss = (win+x)/(win+x+loss);
            if(winLoss < desiredWinLoss)
            {
                x++;
            }
        }
        return gamesToDWL = x;
    }
}

import java.util.*;
public class WinLossTester
{
    public static void main(String []args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter the amount of matches you've won: ");
        int wins = in.nextInt();

        System.out.print("\nEnter the amount of matches you've lost: ");
        int losses = in.nextInt();

        System.out.print("\nEnter your desired match win percentage (eg. 75.4): ");
        double desiredWLP = in.nextDouble();

        System.out.println();

        WinLossCalculator one = new WinLossCalculator(wins, losses, (desiredWLP / 100));

        one.winPercent();
        one.howManyToWinloss();

        System.out.printf("Win percentage: %6.1f", (one.winPercent()*100));
        System.out.print("%");
        System.out.printf("\nLoss percentage: %5.1f", (one.lossPercent()*100));
        System.out.print("%");
        System.out.println("\nVictories required to reach desired W/L percent (without loss): " + one.howManyToWinloss());
    }
}

此外 - 我觉得我的测试人员类的输出部分有点难看,有人可能有任何关于格式化或清理输出部分代码的建议吗?

1 个答案:

答案 0 :(得分:0)

好吧,显然它与我没有联系我的for循环中的第一行加倍像winLoss = (double)(win+x)/(double)(win+x+loss);我不知道为什么会破坏它,但是,这就是为什么它被打破了。