C++ 使用结构计算工资和加班时间。

C++ Calculating wage earned and overtime using a structure.

我想弄清楚我的代码有什么问题。我必须使用一个结构来提示用户输入工作人员 IDNumber、hoursWorked 和 hourlyWage。我的 idNumber、hoursWorked 和 hourlyWage 运行良好,但问题出在我的计算函数上。我不知道如何计算加班收入的 1.5 倍,以及如何将其打印到屏幕上。我不断得到一堆奇怪的数字。

</p> <pre><code>#include<iostream> using namespace std; struct Worker { int idNumber; int hoursWorked; double hourlyRate; double earned; }; void input(Worker & theData); //Postcondition: theData.idNumber, theData.hoursWorked, and theData.hourlyRate are given input values // the user must input into these values. void print(const Worker &); void calc(Worker & theWage); void main() { Worker Data; input(Data); print(Data); system("pause"); } void input(Worker & theData) { cout << "Enter the Employee idNumber"; cin >> theData.idNumber; cout << "Enter the Hours Worked."; cin >> theData.hoursWorked; cout << "Enter the HoutlyRate for under 41 hours."; cin >> theData.hourlyRate; } void print(const Worker & w) { cout << w.idNumber << "\n" << w.hoursWorked << "\n" << w.hourlyRate << "\n" << w.earned << endl; } void calc(Worker & theWage) { if (theWage.hoursWorked <= 40) { theWage.earned = theWage.hoursWorked * theWage.hourlyRate; } else { int basePay; basePay = theWage.hoursWorked * theWage.hourlyRate; theWage.earned = (theWage.hoursWorked - 40) * 1.5 + basePay; } }

您的 calc() 函数必须在 main 中在您的 print() 函数之前调用。

void main()
{
Worker Data;
input(Data);
calc(Data);  // This line was forgotten.
print(Data);
system("pause");
}

您看到的奇怪数字是未初始化的 earned 变量。