[英]Calculation not returning correct value
QUANTITY DISCOUNT 10-19 20% 20-49 30% 50-99 40% 100 or more 50%
编写一个程序,询问所售出的产品数量并计算购买总成本。 输入验证:确保单位数大于0“
这是我到目前为止的内容:
#include <iostream> #include <string> //String class- a string of text #include <iomanip> //Required for setw= the field width of the value after it using namespace std; int main() { double sales, charges, numOfUnits = 0, rateA = .20, rateB = .30, rateC = .40, rateD = .50; //Set the numeric output formatting: cout << fixed << showpoint << setprecision(2); cout << "Enter the quantity for your order: "; cin >> sales; // Determine the discount: double PRICE=99.0; if (sales >= numOfUnits) if (sales >= 10 && sales <= 19 ) rateA; charges = PRICE - rateA *sales; if (sales >= 20 && sales <= 49) rateB; charges = PRICE - rateB *sales; if (sales >= 50 && sales <= 99) rateC; charges = PRICE - rateC *sales; if (sales > 100 ) rateD; charges = PRICE - rateD *sales; cout << "Your total price for this quantity is: $" <<charges << " per unit."<< endl; cout << "That is an invalid number. Run the program again\\n " << "and enter a number greater than\\n" << numOfUnits << ".\\n"; }
编译后,输出未给出正确答案。 也许我的数学错了,或者我的流失了? 有什么建议么?
我不希望有人为我写这个,但也许给我一些指导
您需要在多行情况下使用大括号{}
if (sales >= 10 && sales <= 19 )
rateA;
charges = PRICE - rateA *sales;
实际上是
if (sales >= 10 && sales <= 19 )
rateA;
charges = PRICE - rateA *sales;
即, rateA
执行rateA
并且始终执行charges
更新。
另外,诸如rateA;
语句rateA;
无效,因此应更新或删除。
这种构造:
if (sales >= 50 && sales <= 99)
rateC;
charges = PRICE - rateC *sales;
作用:
if (sales >= 50 && sales <= 99)
rateC;
charges = PRICE - rateC *sales;
换句话说, charges
始终是使用rateC
计算的,而不是仅在销售额处于相关范围内时才计算。 if语句中的rateC
也是完全无用的-它不会对rateC
进行任何rateC
,只是告诉编译器“先查看该值,然后将其丢弃” [编译器可能将其翻译为“ do”。完全没有任何内容”,因为“查看” rateC
实际上在该语句之外没有任何可见的效果,因此可以将其删除]。
乍一看,我认为数学有点过时了。
它应该是 :
double originalPrice = PRICE * sales;
if (sales >= 10 && sales <= 19 )
charges = originalPrice - (rateA * originalPrice);
else if (sales >= 20 && sales <= 49)
等等..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.