gpt4 book ai didi

java - 如何进行折扣计算

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:52:40 25 4
gpt4 key购买 nike

编程新手。如果用户超过 60 岁(年龄>60),我希望用户获得 10% 的折扣,如果他/她超过 55 岁且等于 60 岁,则获得 5% 的折扣。(60<=年龄>55)。我知道我的代码完全错误,但如果可能的话,我想逐步解决这个问题。

import java.util.*;
public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int price, age;
double tax, payAmount;
double discountRate_56_to_60 = 0.05;
double discountRate_60_above = 0.1;
payAmount = price * tax;

System.out.print("Price?");
price = input.nextInt();

System.out.print("Tax(%)?");
tax = input.nextDouble();

System.out.print("Age?");
age = input.nextInt();

System.out.println("You pay: $");
payAmount = input.nextDouble();

if (age > 55) {
payAmount;
}
else if (age >= 60) {
payAmount;
}

}
}

最佳答案

你犯了一些错误:

  • payAmount = price * tax; 行执行得太早了。在从用户那里获取价格和税费之前,如何计算支付金额?

  • payAmount = input.nextDouble(); 不应该存在。该问题应该输出 payAmount,而不是要求它作为输入。

  • payAmount 不是声明。

  • 您的 if 语句似乎有误。如果年龄不大于 55 岁,则永远不能大于或等于 60 岁。

这里是固定代码,更正写在注释中:

Scanner input = new Scanner(System.in);
int price, age;
double tax, payAmount;
double discountRate_56_to_60 = 0.05;
double discountRate_60_above = 0.1;

System.out.print("Price?");
price = input.nextInt();

System.out.print("Tax(%)?");
tax = input.nextDouble();

payAmount = price * tax; // I moved the line here!

System.out.print("Age?");
age = input.nextInt();

// removed the line asking for pay amount

if (age > 60) { // first we check if age is greater than 60. If it is not, then we check if it is greater than 55.
// with a little analysis you will see that this is equivalent to the stated conditions
payAmount -= payAmount * discountRate_60_above; // calculate the payAmount by subtracting the pay amount times discount rate
}
else if (age > 55) {
payAmount -= payAmount * discountRate_56_to_60;
}

System.out.println("You pay: $" + payAmount); // finally output the payAmount

关于java - 如何进行折扣计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com