2012-09-17 115 views
0

我有一个骰子游戏检查,看看谁在骰子游戏

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主

,现在赢了,我有 -

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()中的循环做什么?

感谢

+0

而不是中断;在前两种情况下使用返回false。 –

回答

2
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; 
     } 
    } 
+0

它仍然行为怪异... – user15169

+0

它确实显示7,而不是显示“你赢了”它要求再次发挥,... – user15169

+0

你也有额外的userGame();在while循环之前呼叫... – Borgleader