不知道如何向我的程序添加循环...?

Don't know how to add loop to my program...?

本文关键字:添加 循环 程序 我的 不知道      更新时间:2023-10-16

好吧,有人告诉我用"switch语句"写一个石头/纸/剪刀游戏。我完成了,但今天在课堂上我们被要求在现有游戏中添加一个循环。我了解for循环和while循环的基本知识,但我不知道如何将它们添加到现有程序中。哪一个更好用?我该怎么办?

谢谢各位

因此,我再次理解for循环和while循环的基本原理。但我不明白我是否还需要声明什么,我需要输入什么来接收正确的输出/循环。

#include <iostream>
using namespace std;
int main()
{ // opening bracket 
int game;
cout <<"Let's play Rock, Paper, Scissors nEnter 1 for rock, 2 for paper,3 for scissors"<< endl ;
cin >> game;
switch(game)
{
case 1:
cout << "You chose rock" << endl;
break;
case 2:
cout << "You chose paper" << endl;
break;
case 3:
cout << "You chose scissors" << endl;
break;
default:
cout<<game << " is not a valid choice"<< endl;
}
} // closing bracket  

以下是我的教授的指示:

创建石头,纸,剪刀游戏的第二部分。增强实验室5,以便用户在输入"Y"时一直播放。让这个案例有意义;如果他们输入小写y,游戏将不会继续。如果用户输入除大写Y以外的任何字符,则游戏将结束。

您的文本必须与以下示例完全匹配:

输入正确的示例1让我们玩石头,纸,剪刀输入1表示岩石,输入2表示纸张,输入3表示剪刀2.你选择了纸张你想再玩一次吗(Y表示是,N表示否)?Y输入1表示岩石,输入2表示纸张,输入3表示剪刀1.你选择了摇滚你想再玩一次吗(Y表示是,N表示否)?N输入错误的示例2让我们玩石头,纸,剪刀输入1表示岩石,输入2表示纸张,输入3表示剪刀5.5不是一个有效的选择你想再玩一次吗(Y表示是,N表示否)?y

观看一些youtube视频或阅读循环的基本知识可能是最好的选择。无论如何,这里有一个非常简单的方法来理解这个

#include <iostream>
int main(){
char choice = 'Y';
//enter this loop since 'choice' equals Y
while(choice == 'Y'){
//run the game
//if they enter anything else other than Y, it will stop the loop
std::cout << "Would you like to play again (Y for yes, N for no)? n";
std::cin >> choice;
}
return 0;
} 

以下是您现在拥有的:

//some code that plays a game

以下是您想要的:

while player wishes to continue playing
//same code that plays the game
end while

或者使用for循环,但退出时会有所不同,你需要"突破"它

You can also make use of infinite loop to make it work.
#include <iostream>
using namespace std;
int main()
{ // opening bracket 
int game;
while(1) //you can comment this line and uncomment below line rest all will be same
//for(;;) 
{
cout << "nLet's play Rock, Paper, Scissors n Enter "1" for rockn Enter "2" for papern Enter "3" for scissorsn **Press any other key to exit from the game." << endl ;
cout << "nYour option is : ";  
cin >> game;
switch(game)
{
case 1:
cout << "You chose rockn" << endl;
break;
case 2:
cout << "You chose papern" << endl;
break;
case 3:
cout << "You chose scissorsn" << endl;
break;
default:
cout << game << " is not a valid choicen"<< endl;
return 0;
}
}
} // closing bracket