为什么第二个代码给出了预期的结果,而第一个代码却没有?
Why is it that the second code gives the desired result while the first doesn't?
当我使用函数时,我得到了想要的结果,即:-
1(命令窗口要求我每次都输入,这样我就可以根据需要多次输入"q",甚至可以输入"e"退出
2(每次按"q"分数都会减少1
而在没有函数的代码中,会发生以下情况:-
1(我按"q",分数无限期地下降
2(一旦输入"q",就无法输入另一个输入,例如"e">
#include<iostream>
using namespace std;
int main()
{
char h;
cin>>h;
int n = 10;
do{
system("cls");
cout<<"score is"<<n;
if(h == 'q')
{
n=n-1;
}
}while(h != 'e');
return 0;
}
代码 2 与功能:-
#include<iostream>
using namespace std;
char input;
int n = 10;
bool over = false;
void ip()
{
system("cls");
cout<<"score is"<<n;
cin>>input;
switch(input)
{
case 'q':
n--;
break;
case 'e':
over = true;
break;
}
}
int main()
{
do{
ip();
}while(!over);
return 0;
}
请向我解释程序如何循环遍历函数以及它如何单独循环通过"IF"语句。因为条件语句也存在于函数中(switch 语句(,那么为什么函数不无限期地降低分数或"n"的值呢?
我在第一个代码(没有函数(中发现了我的错误,cin>>
语句应该在do
-while
循环中,以便在每个循环输入之后被询问。
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- 为什么我的代码在第一个 if 语句处中断?
- 我正在尝试在Visual Studio 2013中编写我的第一个"Hello World"代码。为什么我会收到"IntelliSense: no operator message"和"error C2
- 我正在尝试实现 BFS 并通过边缘计算所有访问的节点。但是我的代码给了我 0 计数,除了第一个
- 调试C++代码:捕获第一个 NaN 外观
- 为什么第一个gets()在这段代码中不起作用?
- 为什么我的代码在第一个for循环后停止运行?
- 代码是打印相同的值时,它应该随机生成每一次,而且它不打印数组中的第一个值
- 如果此代码中的答案为"N",我该如何转到第一个 while 循环: