【问题标题】:Cannot exit while loop with boolean condition c++ [closed]无法使用布尔条件c ++退出while循环[关闭]
【发布时间】:2014-11-10 23:15:58
【问题描述】:

您好,这是我的第一篇文章。如果我没有遵守某些规则或约定,我深表歉意。如果是这种情况,请告诉我。

我有一个游戏在 while 循环中运行,直到任一玩家达到分数限制,此时另一个玩家有最后一次(迭代)机会击败第一个玩家得分。然而,在达到分数限制后,循环继续运行,并且永远不会检查获胜者。

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using namespace std;

int roll();
int playTurn(int);

int main(){

const int LIMIT = 5;
int whoseTurn = 1;
int pnts1 = 0;
int pnts2 = 0;
bool suddenDeath = false; //True when score limit is reached



while(!suddenDeath){

    if(pnts1 >= LIMIT || pnts2 >= LIMIT){                       //Limit was reached by previous player.
        suddenDeath == true;                                    //Next player has 1 turn to win

    }   

    if(whoseTurn == 1){
        pnts1 += playTurn(whoseTurn);                           //Play turn and tally points
        whoseTurn = 2;                                          //Swith player for next iteration
    }
    else if(whoseTurn == 2){
        pnts2 += playTurn(whoseTurn);
        whoseTurn = 1;
    }

    cout << "-------------------------------------" << endl     //Display score
         << "Player 1 has " << pnts1 << " points" << endl
         << "Player 2 has " << pnts2 << " points" << endl
         << "-------------------------------------" << endl << endl;

};

if(pnts1 > pnts2)
    cout << "Congratulations Player 1! You won with a score of: " << pnts1 << " - " << pnts2;
else if(pnts2 > pnts1)
    cout << "Congratulations Player 2! You won with a score of: " << pnts2 << " - " << pnts1;
else if(pnts1 == pnts2)
    cout << "A tie! What are the chances?";

return 0;

}

【问题讨论】:

  • 您的意思是 suddenDeath = true; 而不是 suddenDeath == true;

标签: c++ loops while-loop boolean exit


【解决方案1】:
suddenDeath == true;
//          ^^

是一个表示“比较这两个值”的表达式,然后将其丢弃。 C 语句42; 同样有效,同样无用(a)

你想分配这个值,所以你会使用:

suddenDeath = true;
//          ^

这实际上是更常见的if (a = 0) 问题的另一端,人们分配而不是比较。


(a) 如果您想知道为什么任何头脑正常的人都会允许将其用于一种语言,它实际上允许使用最少的代码实现一些强大的构造。

而且,您很可能以前见过它。声明i++; 就是这样的野兽。这是一个表达式,给出了i(您在此处丢弃)具有副作用i 之后会递增。

【讨论】:

    【解决方案2】:
    suddenDeath = true;  
    

    使用单个= 进行分配。 == 用于条件检查。

    【讨论】:

      猜你喜欢
      • 2018-03-18
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多