You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 06:36:03