在使用c++的if语句计算工资和佣金时遇到麻烦

Trouble calculating salary with commission using if statements C++

本文关键字:金时 麻烦 遇到 计算 c++ 语句 if      更新时间:2023-10-16

在这个程序中,我们将计算销售人员的工资和佣金。他每小时的报酬是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";
//...