得到错误的结果

时间:2016-09-04 20:11:15

标签: java

当我输入10个包时,我得到了正确的结果但是当我输入58时,我得到了错误的结果。

我的输出:

Enter the number of packages purchased: 58
Your total without discount: 5742.0
The discount is: 1148.4
The discounted total: 4593.6

应该拥有什么:

Enter the number of packages purchased: 58
Your total without discount: 5742.0
The discount is: 2411.6
The discounted total: 3330.3  

package pkg;

import java.util.Scanner;

public class Hello {
    public static void main(String[] args) {
        double packageCost = 99.00;
        Scanner user_input = new Scanner(System.in);
        System.out.print("Enter the number of packages purchased: ");
        int askPackage = user_input.nextInt();
        double withoutDiscount = packageCost * askPackage;
        double firstDiscount = (packageCost * askPackage) - (withoutDiscount * .20);
        double secondDiscount = (packageCost * askPackage) - (withoutDiscount * .33);
        double thirdDiscount = (packageCost * askPackage) - (withoutDiscount * .42);
        double fourthDiscount = (packageCost * askPackage) - (withoutDiscount * .49);
        System.out.println("Your total without discount: $" + withoutDiscount);
        if (askPackage >= 10 || askPackage <= 19) {
            System.out.println("The discount is: $" + withoutDiscount * .20);
            System.out.println("The discounted total: $" + firstDiscount);
        } else if (askPackage >= 20 || askPackage <= 49) {
            System.out.println("The discount is: $" + withoutDiscount * .33);
            System.out.println("The discounted total: $" + secondDiscount);
        } else if (askPackage >= 50 || askPackage <= 99) {
            System.out.println("The discount is: $" + withoutDiscount * .42);
            System.out.println("The discounted total: $" + thirdDiscount);
        } else if (askPackage >= 100) {
            System.out.println("The discount is: $" + withoutDiscount * .49);
            System.out.println("The discounted total: $" + fourthDiscount);
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

您应该在if else语句中使用&&而不是||。所有可能的输入都在您的第一个条件askPackage >= 10 || askPackage <= 19中处理。因此,只有10-19之间的输入才能为您提供真正的输出。

P.S。你可以这样做折扣分配:

double firstDiscount = (withoutDiscount * .80);

或更好的解决方案;创建一个公共discount变量并将其分配到if-else语句中。