[英]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
循环中,以便在每个循环输入之后被询问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.