【发布时间】:2020-02-06 14:30:25
【问题描述】:
我正在尝试做java作业,场景如下:
对所有消费的商品和服务征收 7% 的销售税。所有价格标签都必须包含销售税。例如,如果一件商品的标价为 107 美元,则实际价格为 100 美元,其中 7 美元用于缴纳销售税。
编写程序,使用循环连续输入含税价格(如“double”);计算实际价格和销售税(“双”);并打印四舍五入到小数点后 2 位的结果。程序将响应输入 -1 终止;并打印总价、总实际价格和总销售税。
但是,当我尝试计算销售税时,而不是显示:
输入·本·含税·价格·in·美元·(或·-1·到·结束):107
实际·价格·是:$100.00
销售额·税收·是:$7.00
我的计算表明:
以美元为单位输入含税价格(或 -1 结束):107
实际价格为 99.51 美元
销售税为:7.49 美元
我不确定我的编码有什么问题。
import java.util.Scanner;
public class SalesTax{
public static void main(String[] args) {
// Declare constants
final double SALES_TAX_RATE = 0.07;
final int SENTINEL = -1; // Terminating value for input
// Declare variables
double price, actualPrice, salesTax; // inputs and results
double totalPrice = 0.0, totalActualPrice = 0.0, totalSalesTax = 0.0; // to accumulate
// Read the first input to "seed" the while loop
Scanner in = new Scanner(System.in);
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = in.nextDouble();
while (price != SENTINEL) {
// Compute the tax
salesTax = SALES_TAX_RATE * price;
actualPrice = price - salesTax;
// Accumulate into the totals
totalPrice = actualPrice + salesTax;
totalActualPrice = actualPrice + actualPrice;
totalSalesTax = salesTax + salesTax;
// Print results
System.out.println("Actual price is $" + String.format("%.2f",actualPrice));
System.out.println("Sales Tax is: $" + String.format("%.2f",salesTax));
// Read the next input
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = in.nextDouble();
// Repeat the loop body, only if the input is not the sentinel value.
// Take note that you need to repeat these two statements inside/outside the loop!
}
// print totals
System.out.println("Total price is: " + String.format("%.2f",totalPrice));
System.out.println("Total Actual Price is: " + String.format("%.2f",totalActualPrice));
System.out.println("Total sales tax is: " + String.format("%.2f",totalSalesTax));
}
}
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: java