【问题标题】:Output error resulting from logic error when determining percentage based on incremental while loop基于增量while循环确定百分比时由于逻辑错误导致的输出错误
【发布时间】:2014-04-19 01:56:24
【问题描述】:

我创建了一个简单的类,它计算赢/输百分比并返回必要的连续赢的数量,以根据给定的赢、输、和期望的赢/输。但是,在运行程序时,我注意到输出给出了一个非常大的数字,而不是一个相对较小的数字(所需的获胜次数)。我不确定我犯了什么错误导致了这个错误,但我确定它与位于我的 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());
    }
}

另外——我觉得我的测试器类的输出部分有点难看,有人对格式化或清理输出部分的代码有什么建议吗?

【问题讨论】:

    标签: java loops for-loop logic


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      相关资源
      最近更新 更多