C++:输入某个输入时计算不正确

标签 c++

我断断续续地自学了几个月的 C++,现在我正在尝试制作一个薪资系统。这是我的代码:

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;
void wageCompute (int, int);

int main()
{
    int loopTimes=0;
    int empNum=100, workHours, otHours, rate, bPay, otPay, grossPay;
    string empName, empPos;
    cout << "PAYROLL FOR THE MONTH OF MARCH" << endl;
    cout << "Employees: " << empNum << endl;
        while (empNum>loopTimes)
            {
                cout << "NAME: ";
                cin.ignore();
                getline (cin, empName);
                cout << "\nPOSITION: ";
                getline (cin, empPos);
                cout << "\nHOURS WORKED: ";
                cin >> workHours;
                cout << "\nWAGE PER HOUR: ";
                cin >> rate;
                bPay = workHours*rate;
                cout << "YOUR BASE PAY IS: " << bPay << endl << endl;
                cout << "HOURS WORKED OVERTIME: ";
                cin >> otHours;
                otPay = (1.5*rate)*otHours;
                cout << "\nOVERTIME PAY: " << otPay << endl;
                grossPay = bPay + otPay;
                cout << "GROSS PAY: " << grossPay << endl;
                wageCompute(bPay, grossPay);

                loopTimes++;
            }
    return EXIT_SUCCESS;
}
void wageCompute(int bPay, int grossPay)
{
     double rate, dedInsurance, dedMedical, totDeduct, netPay, tax;
        if (bPay<10001)
        {
            rate = 0.05;
        }
       else if (bPay<15001)
        {
            rate = 0.1;
        }
        else if (bPay<20001)
        {
            rate = 0.15;
        }
        else
        {
            rate = .2;
        }

    tax = bPay*rate;
    dedInsurance = bPay*0.05;
    dedMedical = bPay*0.01;
    totDeduct = tax + dedInsurance + dedMedical;
    cout << "TAX: " << tax << endl;
    cout << "SSS DEDUCTION: " << dedInsurance << endl;
    cout << "Medicare DEDUCTION: " << dedMedical << endl;
    cout << "TOTAL DEDUCTIONS: " << totDeduct << endl;
    netPay = grossPay - totDeduct;
    cout << "NET PAY: " << netPay << endl;
}

出错的部分是当我为工作时间、每小时工资和加类时间输入特定值时。程序检查基本工资是否应该扣除适当的税额,我输入的是工作时间160,每小时工资100,加类费10。我已经尝试减少和增加它并且它工作得很好似乎只是这些数字组合是它出错的部分。

输出截图: http://i.stack.imgur.com/BpJHs.png

最佳答案

您的问题不是很清楚,但我怀疑您在这里看到的是众所周知的 float 限制;很容易以 10 为基数精确表示的数字在 2 进制中没有精确表示。一个例子:0.1 以 10 为基数是 0.0001100110011…以 2 为基数重复;近似值的准确性取决于人们愿意使用多少位来写入它。

另一种方法是使用已知精度​​的整数运算,假设您要计算到最接近的百分之一便士(我在这里使用的是英国货币)。将 1.01 英镑表示为 10100,当您完成的 val/10000 是英镑,(val % 10000)/100 是便士。如果需要,您可以围绕便士的四舍五入实现一些更复杂的规则。

关于C++:输入某个输入时计算不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22279374/

相关文章:

c++ - 搜索时 vector 键丢失

c++ - 对象数组的 vector - push_back()

c++ - 是否有防止 STL 容器被交换的 C++ 分配器?

c++ - 看不懂std::move的实现

c++ - 将字符串流解析为字符串和 double

c++ - 这个语法是什么? C++

c++ - GOTO 还是不 GOTO?

c++ - 如何编译和链接单元测试?

C++/Qt 全局热键

c++ - 为什么 atoi 函数不能将 const char * 转换为 int?