【发布时间】:2021-08-25 20:58:57
【问题描述】:
我正在用 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;
}
【问题讨论】:
-
overtime_hours_worked = hours_worked_inweek-40;必须在cin >> hours_worked_inweek;之后,因为你现在从 0 中减去 40,所以 -40。 -
其中定义了许多变量但未初始化。在使用它们之前,请确保它们都设置为有用的东西,但最好不要定义它们,直到你尽可能地获得它们的初始值。没有未初始化的变量可以防止很多琐碎的错误
-
当您在 Stack Overflow 上提问时,您应该将您的程序缩减为 minimal reproducible example。不要发布整个代码;仅发布证明问题所需的内容。在这种情况下,您只需要 6 行,不是吗? (
int hours_worked_inweek=0;int overtime_hours_worked=0;overtime_hours_worked = hours_worked_inweek-40;cout << " How many hours have you worked in a week ? " << endl;cin >> hours_worked_inweek;cout<<hours_worked_inweek<< "-" << "40" << " Which is equal to " << overtime_hours_worked<<endl;) -
我会发表关于解决编译器警告的评论,但我猜你已经这样做了。我注意到您初始化的唯一两个变量是公式中使用的变量。您的编译器是否试图警告您您的设置错误(使用未初始化的变量),但您通过初始化为零而不是修复真正的错误来使其静音?