为什么第二个代码给出了预期的结果,而第一个代码却没有?

Why is it that the second code gives the desired result while the first doesn't?

本文关键字:代码 第一个 结果 第二个 为什么      更新时间:2023-10-16

当我使用函数时,我得到了想要的结果,即:-

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循环中,以便在每个循环输入之后被询问。