繁体   English   中英

计算未返回正确值

[英]Calculation not returning correct value

我被要求编写以下程序: “一家软件公司出售的零售价为99美元的软件包。根据下表提供数量折扣:
 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM