C++加班工时计算程序运算异常,输入48小时得到-40而非预期值8
问题原因与修复方案
你的问题出在变量计算的执行顺序错误:
- 你在读取用户输入的周工时前就执行了
overtime_hours_worked = hours_worked_inweek-40计算,此时hours_worked_inweek还是初始化的0值,所以overtime_hours_worked被固定赋值为0-40=-40,后续读取用户输入的48后也没有重新计算该变量,因此输出结果和预期不符。 - 此外你写的
overtime_rate = 1.5*overtime_hours_worked逻辑本身错误,加班工资倍率应为固定的1.5倍时薪,不需要和加班时长相乘。
修正后可正常运行的代码
#include<iostream> using namespace std; int main(){ int hours_worked_inweek=0; int dependents; int union_dues; double federal_tax_witholding; double state_tax_witholding; double social_security_tax_witholding; double gross_pay; double net_pay; double hourly_rate; double overtime_rate; int overtime_hours_worked=0; // 固定参数提前赋值 hourly_rate = 16.76; overtime_rate = 1.5 * hourly_rate; union_dues = 10; cout << " How many hours have you worked in a week ? " << endl; cin >> hours_worked_inweek; cout << "Wow ! You worked "<<hours_worked_inweek<<" this week"<<endl; // 拿到用户输入的周工时后再计算加班时长 overtime_hours_worked = hours_worked_inweek - 40; if (hours_worked_inweek>40){ cout<<"It looks like you also worked some overtime hours this week! Your Overtime hours are : "<<endl; cout<<hours_worked_inweek<< "-" << "40" << " Which is equal to " << overtime_hours_worked<<endl; } else{ cout<< " You did not work any overtime hours this week !"<<endl; } cout<< "How many dependents do you have : "<<endl; cin>>dependents; return 0; }
内容的提问来源于stack exchange,提问作者Intisar Ratul
相关产品推荐
相关产品推荐

