在使用c++的if语句计算工资和佣金时遇到麻烦
Trouble calculating salary with commission using if statements C++
在这个程序中,我们将计算销售人员的工资和佣金。他每小时的报酬是10美元,再加上销售数量的佣金。前50件他不收钱,后50件(51-100件)他赚1美元佣金。101-300,他赚2美元,300+,他赚5美元。输出应该看起来像这样(小时* 10 + 50*0 + 50*1 +200*2 + 100*5),但我不知道如何得到它。谢谢你的建议
#include <iostream>
#include <string>
using namespace std;
bool error(const string & msg);
int main() {
double hours;
double widgets;
cout << "How many hours did you work this month and how many widgets did you sell? " << endl;
cin >> hours >> widgets;
if (!cin) error("Your input is invalid");
if (hours < 0) error("Your input can't be negative");
if (widgets < 0) error("Your input can't be negative");
hours = (hours * 10.00); // Salesman gets paid 10$ an hour
if (widgets <= 50) cout << 0; // Salesman doesn't get paid for less than 50 widgets sold
if (widgets > 50 && widgets < 101) cout << widgets * 1.00; // 51-100 Widets sold = 1$ per
if (widgets > 100 && widgets < 301) cout << widgets * 2.00; // 101-300 sold = 2$ per
if (widgets > 300) cout << widgets * 5.00; // anything above 300 = 5$ per
/* my cout should look something like
hours * 10 + 50*0 + 50*1 +200*2 + 100*5
*/
cout << hours + widgets;
}
bool error(const string & msg) {
cout << "Error: " << msg << endl;
exit(EXIT_FAILURE);
}
这可能是一项作业,所以我不会给出答案,但希望能引导你们注意错误。
如果你看看你的逻辑和考虑一些测试输入,你可以很容易地看到为什么它不会像写的那样工作。例如,考虑widgets = 500
。
if (widgets <= 50) cout << 0;
widgets
不等于50,所以这个逻辑不会触发。
if (widgets > 50 || widgets < 101) cout << widgets * 1.00;
widgets
不在[51,100]的范围内,所以这个逻辑不会触发,但是你想在这里进行计算。下一个范围[101,300]也是如此。如前所述,只有最后的逻辑(widgets > 300
)会被触发。
要解决这个问题,您需要在执行计算时保持运行总数。此外,您将希望逻辑为每个适用范围触发。
使用widgets = 500
的相同示例,您希望对所有佣金范围应用计算。有很多方法可以实现这一点,但一般的逻辑是:
- 有一些
widgets
- 如果有超过50个小部件,计算出有多少个,但不超过100个,并将计算应用于总小部件的这个子集,从概念上讲,现在可能有一些剩余的小部件
- 继续处理剩余部件并应用适用的佣金计算,直到没有剩余部件(在达到最终佣金范围后肯定会有剩余部件,因为所有剩余部件都超过300)
如果你希望结果是一个格式化的字符串,不要进行计算。你可以使用的是stringstream。
#include <sstream>
stringstream ss;
ss << hours << " * 10 ";
//...
//at the end
cout << ss;
你也可以用字符串来做,但是必须在cpp代码中添加一些C代码
string cppStr;
char cstr[15];
sprintf(cstr, "%d", hours);
cppStr = cstr;
cppStr += " * 10";
//...
相关文章:
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 查找奇数平方和时遇到麻烦
- CSUF EPP - 你有什么想法(在添加到链接列表末尾时遇到麻烦)
- MySQL 从注入过渡到参数化时遇到麻烦
- C++击球平均值程序使用输入/输出文件打印名称,平均值,最高/最低平均值时遇到麻烦
- 以分类方式插入节点时遇到麻烦
- C 在将数组引用分配给struct时麻烦
- C++释放矢量元素占用的内存时遇到的麻烦
- 编译代码时麻烦 - strncpy char*和string
- 我在处理字符时遇到麻烦
- 在我的代码覆盖本身时遇到麻烦,我不确定为什么
- C++处理文件,在制作程序时遇到麻烦
- 使用MQQueue将数据读取到缓冲区中时麻烦
- 循环时嵌套的麻烦
- 从一个字符串中获取 2-5 个连续的单词短语,我得到了 2 个工作,但在做 3 个时遇到麻烦
- 使用Boost FilesyTem构建时麻烦
- 将向量传递到C 功能时的类型麻烦
- 当我想为结构体声明新成员时,有些麻烦我不明白
- 计算字符时遇到麻烦
- 在C++中摸索多个排他性组合时遇到麻烦