计算未返回正确值

Calculation not returning correct value

本文关键字:返回 计算      更新时间:2023-10-16
我被要求编写这个程序:"一家软件公司出售的软件包零售价为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 againn "
         << "and enter a number greater thann" 
         << numOfUnits << ".n";
} 

编译后,输出没有给我正确的答案。也许我的数学错了,或者我的思维不流畅?有什么建议吗?

我不想让任何人为我写这篇文章,但也许可以给我一些指针

您需要在多行条件周围使用大括号{}

if (sales >= 10 && sales <= 19 )
    rateA;
    charges = PRICE - rateA *sales;

实际上是

if (sales >= 10 && sales <= 19 )
    rateA;
charges = PRICE - rateA *sales;

即有条件地执行CCD_ 2并且总是执行对CCD_。

此外,像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在该语句之外实际上没有任何可见的效果,所以它可以被删除]。

乍一看,我觉得数学有点不对劲。

应该是:

double originalPrice = PRICE * sales;
if (sales >= 10 && sales <= 19 )
  charges = originalPrice - (rateA * originalPrice);
else if (sales >= 20 && sales <= 49)

等等。