2
我被要求写这个程序:“一家软件公司出售一个零售价为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";
} 

编译后,输出没有给我正确的答案。也许我的数学是错误的,或者我的流程是关闭的?有什么建议么?

我不希望任何人为我写这个,但也许给我一些指示

4

3 回答 3

4

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

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

实际上是

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

ierateA有条件地执行,charges并且总是执行更新。

此外,诸如此类rateA;的声明无效,因此应该更新或删除。

于 2013-09-04T17:08:30.723 回答
0

乍一看,我认为数学有点不对劲。

它应该是 :

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

等等..

于 2013-09-04T17:14:56.347 回答
0

这种构造:

if (sales >= 50 && sales <= 99)
rateC;
charges = PRICE - rateC *sales;

做:

if (sales >= 50 && sales <= 99)
    rateC;

charges = PRICE - rateC *sales;

换句话说,charges总是用 计算rateC,而不是仅当销售额在相关范围内时才计算。rateCif 语句内部也完全没用 - 它不会“做”任何事情rateC,它只是告诉编译器“去看看这个值,然后把它扔掉”[编译器可能翻译为“什么都不做” all”,因为“看”在rateC该语句之外实际上没有任何可见的效果,因此可以将其删除]。

于 2013-09-04T17:11:09.890 回答