C++初级"while"课程
Beginner "while" program in C++
我必须解决一个问题,我计算员工的工资,他们在前 10 小时内每小时获得 40 欧元,然后每隔一小时他们获得 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
s 更改为 if
s。
while
内部的条件总是true
的,因为hours
总是小于 40,因为while
条件内部的hours
没有修改,因此会导致无限循环。
修改后的代码:
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;
}
为了使以下循环不是无限的
while (hours <= 40)
{
salary = hours * 10;
cout << "Salary of the employee is: " << salary << endl;
}
循环中的某些内容将不得不以一种会导致hours <= 40
false
的方式修改hours
。
目前,只有salary
在该循环中被修改。
你正在使用 while 循环,就像它们是 if 语句一样。
使用两个变量,一个变量获取工作小时数,另一个变量从 0 开始并计算每个支付的小时数。
int hours;
int hourscounted = 0;
double salary;
int main()
{
cout << "Enter amount of hours worked" << endl;
cin >> hours;
while (hourscounted <= hours)
{
if(hourscounted < 40)
{
salary = salary + 10;
}
else
{
salary = salary + 15;
}
hourscounted++;
}
cout << "Salary of the employee is: " << salary << endl;
system("pause");
return 0;
}
将 while 更改为 if :P 并提示将来 - 不要使用 endl,除非你真的需要这样做。你可以在循环/if语句之外进行打印(cout(。它永远不会结束,while循环,它取决于一些东西,没有改变。
编辑:在更详细地阅读了您的代码和问题之后,似乎您应该用if
替换while
以满足您正在查看的逻辑。
如果您的代码在无限循环中打印,则应始终检查为什么不满足其终止条件。
在您的情况下,循环在hours < 40
(第 1 种情况(和hours > 40
(第 2 种情况(时终止。你没有修改循环中的小时数,所以它被困在一个无限循环中。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- C++初级"while"课程