不知道如何向我的程序添加循环...?
Don't know how to add loop to my program...?
好吧,有人告诉我用"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
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++ 在循环中添加计数器变量并再次初始化其值
- 如何添加循环期间分配的变量?
- 是否可以在 for 循环中添加两个浮点数?
- 需要循环帮助以迭代方式添加到程序集中的总和变量
- 添加#pragma循环后出现Segfault
- 在 C++ 中向 rand() 添加模数会影响 for 循环之外的执行,为什么以及如何补救?
- C++ 循环逐行写入文件还是添加到数组并在循环后写入文件?
- 如何从 while 循环中添加数字
- 循环以使用设置模板类将所有 26 个字母添加到 s 中
- C++在 while 循环后添加一行代码会导致错误
- 为什么if语句和变量声明要比循环中的添加更快
- C++:如何在"for"循环中动态地向文本行添加后缀以创建先前声明的变量
- 为什么可以添加填充使您的循环更快
- 当循环崩溃时,不向数组添加单词
- 不知道如何向我的程序添加循环...?
- 如何在加密++库的AES中找到添加循环密钥和混合列代码
- 如何在c++中添加循环
- 如何添加循环输入文件的结果