我必须解决一个问题,我计算员工的薪水,他们在前 40 小时每小时获得 10 欧元,然后每增加一个小时他们获得 15 欧元。我已经解决了问题,但我的控制台无限循环地打印答案,我不知道我哪里错了。
int hours;
double salary;
int main()
{
cout << "Enter amount of hours worked" << endl;
cin >> hours;
while (hours <= 40)
{
salary = hours * 10;
cout << "Salary of the employee is: " << salary << endl;
}
while (hours > 40)
{
salary = (40 * 10) + (hours - 40) * 15;
cout << "Salary of the employee is: " << salary << endl;
}
system("pause");
return 0;
}
最佳答案
将 while
更改为 if
。
while
中的条件将始终为 true
,因为 hours
将始终小于 40,因为没有修改 hours
在 while
条件内,因此导致无限循环。
修改后的代码:
int hours;
double salary;
int main()
{
cout << "Enter amount of hours worked" << endl;
cin >> hours;
if (hours <= 40)
{
salary = hours * 10;
cout << "Salary of the employee is: " << salary << endl;
}
else //I have removed the condition because if hours is not less than 40,
// it has to be greater than 40!
{
salary = (40 * 10) + (hours - 40) * 15;
cout << "Salary of the employee is: " << salary << endl;
}
system("pause");
return 0;
}
使用 while 循环的解决方案。
既然你一心想得到一个 while
循环解决方案,
代码:
int hours;
int counthour = 0;
double salary;
int main()
{
cout << "Enter amount of hours worked" << endl;
cin >> hours;
while (counthour <= hours)
{
if(counthour <= 40)
salary += 10;
else
salary += 15;
counthour++;
}
cout << "Salary of the employee is: " << salary << endl;
system("pause");
return 0;
}
关于c++ - C++ 初学者 "while"程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28546092/