我有一个骰子游戏
int userGame()
{
cout << " User turn --- Press 2 to roll" << endl;
cin >> userInput;
if ( userInput == 2 )
{
Dice ();
cout << "The user rolled Dice 1 =" << die1 << " and Dice 2 = " << die2 << endl;
cout << "Total = " << die1 + die2 << endl;
}
else {
cout << "Wrong input. Try again";
//userGame();
}
return (die1 + die2);
}
现在在 int main 中,我有 -
int main ()
{
// set the seed
srand(time(0));
userGame();
while (true)
{
if (userGame() == 7 || userGame() == 11)
{
cout << "You won" << endl;
break;
}
else if (userGame() == 2)
{
cout << "You loose" <<endl;
break;
}
else
{
break;
}
}
return 0;
骰子();
#include<iostream>
#include<ctime> // for the time() function
#include<cstdlib> // for the srand() and rand() functions
using namespace std;
int compInput;
int userInput;
int die1 = 0;
int die2 = 0;
int Dice ()
{
// roll the first die
die1 = (rand() % 6 ) + 1;
// roll the second die
die2 = (rand() % 6 ) + 1;
}
但由于某种原因,输出显示不正确。一旦它在输出为 7 和其他时间时显示用户赢了,它就会继续游戏。
我要用 main() 中的循环做什么?
谢谢
最佳答案
if (userGame() == 7 || userGame() == 11)
这一行是你的问题。 C++ 使用短路求值。在这种情况下,如果 userGame() == 7
成功,则不会检查后半部分。但是,如果它失败,将在下半场再次调用 userGame()
,这意味着您将在进入 if 的代码部分之前玩两次。
while (true)
{
int result = userGame();
if (result == 7 || result == 11)
{
cout << "You won" << endl;
break;
}
else if (result == 2)
{
cout << "You loose" <<endl;
break;
}
else
{
break;
}
}
关于c++ - 检查谁在骰子游戏中获胜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451766/