我正在尝试回答以下问题:以下伪代码描述了书店如何根据总价和订购的书籍数量计算订单价格。请编写创建它所需的 java 代码。
- 阅读总书价和书籍数量。
- 计算税收(总书价的 7.5%)。
- 计算运费(每本书 2 美元)。
- 订单价格是总书价、税金和运费的总和。
- 打印订单的价格。
我是编程新手,如果有很多错误,我很抱歉。这是我到目前为止所拥有的:
package test2;
import java.util.Scanner;
public class test2 {
public static void main (String args[]){
Scanner inputfromscanner = new Scanner(System.in);
double bookprice=0, taxpercentage, shippingcharge, totalbeforetax,
totalwithtax, totalwithshipping;
int numbooks;
taxpercentage = 1.075;
shippingcharge = 2;
System.out.print("Please enter the number of books:");
numbooks = inputfromscanner.nextInt();
for(int x=0;x<=numbooks;x++){
if( x == numbooks ) {
break;
}
System.out.print("Please enter the before-tax price of the book:");
bookprice = inputfromscanner.nextDouble();
}
inputfromscanner.close();
totalbeforetax = bookprice;
totalwithtax = totalbeforetax*taxpercentage;
totalwithshipping = totalwithtax + (numbooks*shippingcharge);
System.out.print("The total price of the order is: $");
System.out.println(totalwithshipping);
}
}
输出示例:
Please enter the number of books:5
Please enter the before-tax price of the book:10.50
Please enter the before-tax price of the book:20.50
Please enter the before-tax price of the book:30.50
Please enter the before-tax price of the book:40.50
Please enter the before-tax price of the book:50.50
The total price of the order is: $64.2875
所以我意识到我做错了什么,但我不知道如何解决它。"totalbeforetax=bookprice;" 行不正确。这应该是输入的所有图书价格的总和。所以,在这个例子中,数学将是 totalbeforetax= 10.50 + 20.50 + 30.50 + 40.50 + 50.50 = 152.50。发生的情况是,每次我输入一本书的价格时,它都会被我接下来输入的任何书价覆盖。所以当我输入 40.50 然后 50.50 时,40.50 被抛出,计算中只使用 50.50。
我需要一种方法来独立存储这些书的价格值。我不想创建诸如 bookprice1、bookprice2、bookprice3 等变量。因为我需要它是无限数量的图书价格。我不知道如何告诉它分别保存这些值中的每一个。也许有某种变量我可以告诉它在变量的末尾添加 1 然后将它们加在一起?
另外我不确定“bookprice=0”在做什么。我使用 Eclipse 作为 IDE,它告诉我将其更改为最后具有“=0”。
解释数学。下面是一个示例,如果用户输入了 5 个图书价格:
$10.50 + $20.50 + $30.50 + $40.50 + $50.50 = $152.50 (totalbeforetax)
$152.50 * 1.075 = $163.9375 (totalwithtax)
$163.9375 + ( 5 books * $2 per book shipping fee) = $173.9375 (totalwithshipping)
我假设运费不包括税费,并且运费是在之后添加的,因为问题中没有具体说明。
我的程序在做什么:
$50.50 = $50.50 (totalbeforetax)
$50.50 * 1.075 = $54.2875 (totalwithtax)
$54.2875 + ( 5 books * $2 per book shipping fee) = $64.2975 (totalwithshipping)
另外,我想做的其他事情是让事情看起来很漂亮(这看起来像是小问题,但我认为有复杂的解决方案)就是将答案四舍五入到小数点后 2 位,但我不知道该怎么做. 因此,如果订单的总价格为 64.2875 美元,它只会显示 64.29 美元。(所以我要去掉 2 个数字并同时四舍五入)
我想做的另一件事是,有时答案可能会说“订单的总价格是:65.5 美元”。有没有办法在这个末尾添加一个零,所以它会说 65.50 美元?只有当答案的小数点后有一个数字时,我才能告诉它最后添加一个零?
我希望我已经详细解释了一切。请询问您是否有问题。感谢您的时间和帮助!对此,我真的非常感激!