计算未返回正确值
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 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)
等等。
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 为什么是谷神星协方差.计算()似乎永远运行而不返回?
- 始终在 C++ 计算脚本中返回466750944
- imageLoad glsl 在计算着色器 OpenGL 4.3 中始终返回 0
- 返回一个计算了参数的函数
- 计算BST返回-1的高度混淆
- 我正在尝试创建一个布尔函数,该函数计算字符并在字符为"()*-+"时返回 true
- 计算 <Classtype*> 向量中所有项的布尔值的最有效方法,如果全部为真则返回 true
- 递归计算满足条件的值数并返回该数字
- 从捕获 constexpr 函数返回值的变量中删除 constexpr 会删除编译时计算
- 我正在尝试编写一个简单的计算程序,但答案一直返回为 0
- 为什么当我尝试计算平均绝对偏差时,我的程序返回 inf
- 为什么这个计算二进制搜索树中节点的递归函数总是返回比预期更大的结果
- 计算每秒添加到队列中添加的请求数 - 始终返回为零
- CSV文件中的两条线的交点的计算返回-1.#IND
- friend get 函数,返回通过可变参数模板递归计算的类型
- 创建一个函数,该函数根据边缘转换为给定(浮点)时间值计算布尔返回值
- 如何在递归函数中计算返回结果
- 如何计算并返回指向max元素的指针的值?C++