【问题标题】:Why am I getting the wrong numbers when my loop runs through? [closed]当我的循环运行时,为什么我得到错误的数字? [关闭]
【发布时间】:2022-10-16 05:05:00
【问题描述】:

运行代码后,您输入以下内容:是的,1、1 和 10,系统显示仍有 8.3825 需要支付。从这里开始,如果我输入的值小于 8.3825,我会不断获得随机值。我试图让 while 循环中的总值变为 0 或小于零。我被卡住了,因为我不知道为什么我会得到随机值或它们的含义以便我纠正它们。

import java.util.Scanner;

public class WonderlandRecords {
    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        System.out.println("Would you like to make a purchase: ");
        String no = inp.nextLine();

        boolean x;
        if (no.equals("no")) {
            x = true;
        } else {
            x = false;
        }

        if (x == false) {
            System.out.println("1. The Chronic Vinyl ($19.35)");
            System.out.println("2. Thriller Vinyl ($13.35)");
            System.out.println("3. When We Fall Asleep, Where Do We Go? Vinyl ($15.64)");
            System.out.println("4. Puka Sheel Necklace ($5.00)");
            System.out.println("5. Hacky Sack ($6.73)");
            System.out.println("6. Display Menu");
            System.out.println("7. Checkout");

            inp = new Scanner(System.in);
            System.out.println("What item would you like to order: ");
            int order1 = inp.nextInt();

            inp = new Scanner(System.in);
            System.out.println("If you would like to buy another item enter it and go to checkout or directly go to checkout: ");
            int order2 = inp.nextInt();

            if (order1 == 1 || order2 == 1) {
                boolean discount = true;
                double tot = 38.70;
                System.out.println("Your grand total is $38.70");

                inp = new Scanner(System.in);
                System.out.println("How much would you like to pay: ");
                double userPay = inp.nextInt();

                if (calculateChange(userPay, tot, discount) == 0) {
                    System.out.println("You paid the exact amount");
                }

                while (calculateChange(userPay, tot, discount) > 0) {
                    System.out.println(calculateChange(userPay, tot, discount) + " is your new total");

                    tot = calculateChange(userPay, tot, discount);

                    inp = new Scanner(System.in);
                    System.out.println("How much would you like to pay: ");
                    userPay = inp.nextInt();
                }
            }
        }
    }

    public static double calculateChange(double userPay, double tot, boolean discount) {
        if (discount == true) {
            tot = (tot - (tot * 5 / 100)) - userPay;
        } else {
            tot = tot - userPay;
        }
        return tot;
    }
}

【问题讨论】:

  • 你忘了解释你想要做什么,你期望什么输出,为什么,你为解决问题采取了哪些步骤,你在哪里卡住了。
  • 这些不是你说的“随机值”。这些是舍入误差。有两种方法可以解决这个问题,一种是拆分美元和美分并分别执行计算,或者通过添加依赖项使用 javamoney api。看这篇文章Baeldung java money

标签: java


【解决方案1】:

if (discount = true) {

在这里,您强制 discount 始终为真并输入以下代码块。

【讨论】: