首页 > 解决方案 > 计算加班时间时程序计算错误

问题描述

我正在用 C++ 编写一个计算加班时间的程序。由于某种原因,计算overtime_hours_worked是遥不可及的。我尝试初始化变量和否定。我为 hours_worked_inweek 输入了 48 小时,根据我的公式,我应该得到 8 作为答案。相反,我得到-40。我目前正在学习。

#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;
    
    overtime_rate = 1.5*overtime_hours_worked;
    hourly_rate = 16.76;
    union_dues = 10;
    overtime_hours_worked = hours_worked_inweek-40;
    
    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;
    
    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;
}

标签: c++math

解决方案


看看这条线overtime_hours_worked = hours_worked_inweek-40;,停一下。在那一刻,时间变量hours_worked_inweek等于 0,因为您在第一行对其进行了初始化。但是您想从用户的输入中减去 40,因此在此处获得输入后只需移动此行cin >> hours_worked_inweek;


推荐阅读