2016-02-12 124 views
-3

这是函数:如何退出循环,如果一个函数返回一个值

void LoseRollDice(int Result1, int Result2, int i) 
{ 
    if (i == 1 && (Result1 == 2 || Result1 == 3 || Result1 == 12)) 
    { 
     cout << "You Lose." << endl; 
     return; 
    } 
    else if (i == 1 && (Result2 == 2 || Result2 == 3 || Result2 == 12)) 
    { 
     cout << "Computer Loses." << endl; 
     return; 
    } 
    if (Result1 == 7 && i > 1) 
    { 
     cout << "You Lose." << endl; 
     return; 
    } 
    if (Result2 == 7 && i > 1) 
    { 
     cout << "Computer Loses." << endl; 
     return; 
    } 
} 

在这里,我用它:

for (int i = 1; i <= 5; i++) 
{ 
    cout << "Enter 1 to play, or 2 to exit: "; 
    cin >> chose; 
    cout << endl; 
    if (chose == 1) 
    { 
     ResultPlayer = RollDice(); 
     ResultComputer = RollDice(); 
     DisplayDice(ResultPlayer, ResultComputer, i); 
     cout << endl; 
     LoseRollDice(ResultPlayer, ResultComputer, i); 
     // if the player lose, how to break after this function if the condition is true in it?? 
     WinRollDice(ResultPlayer, ResultComputer, i, SumPlayer, SumComputer); 
    } 
    else break; 
} 

如何摆脱for循环,如果条件功能是否正确? 如果我把循环就会爆发,即使条件不满足

+1

你需要让函数返回一些东西,并根据返回的内容继续或结束循环。 – NathanOliver

+0

我曾想过要像你说的那样做,但我认为这不是最好的休息方式! –

回答

3

更改LoseRollDice到循环的功能后突破:

bool LoseRollDice(int Result1, int Result2, int i) 
    { 
    if (i == 1 && (Result1 == 2 || Result1 == 3 || Result1 == 12)) 
    { 
     cout << "You Lose." << endl; 
     return true; 
    } 
    else if (i == 1 && (Result2 == 2 || Result2 == 3 || Result2 == 12)) 
    { 
     cout << "Computer Loses." << endl; 
     return true; 
    } 
    if (Result1 == 7 && i > 1) 
    { 
     cout << "You Lose." << endl; 
     return true; 
    } 
    if (Result2 == 7 && i > 1) 
    { 
     cout << "Computer Loses." << endl; 
     return true; 
    } 
    return false; 
} 

然后你的其他代码:

for (int i = 1; i <= 5; i++) 
{ 
    cout << "Enter 1 to play, or 2 to exit: "; 
    cin >> chose; 
    cout << endl; 
    if (chose == 1) 
    { 
     ResultPlayer = RollDice(); 
     ResultComputer = RollDice(); 
     DisplayDice(ResultPlayer, ResultComputer, i); 
     cout << endl; 
     if (LoseRollDice(ResultPlayer, ResultComputer, i)) 
      break; 
     WinRollDice(ResultPlayer, ResultComputer, i, SumPlayer, SumComputer); 
    } 
    else break; 
} 
+0

谢谢你的帮助:) –

+0

@OlegGrytsenko你说什么呢?我想要做你喜欢的事情,但我认为这不是破解的最佳方式!*? – NathanOliver

0

道格拉斯道森的回答是正确的。如果您确实真的很想让该方法无效,那么您也可以让该方法抛出异常,然后在循环外捕获该异常。这是一个绝对可怕的方式来实现它。

或者你可以抓住它的循环,并呼吁break;

0

或者使用指针...发送相同的参数功能..如果..更改里面的指针值后,如果您调用函数检查点..如果这是改变意味着如果被称为..你可以打破你的循环。

相关问题