while 语句如何限制循环次数?

请问在下面这个“猜数字游戏”代码中怎么限定玩家猜测的次数,比如我希望在玩家猜测5次的时候显示游戏失败,那该如何添加代码呢?

int main()
{
    srand((unsigned int)time(NULL));
    int num = rand() % 100 + 1;
    cout << num << endl;

    int a = 0;

    while (1)
    {
        cin >> a;
        if (a > num)
        {
            cout << "猜测过大" << endl;
        }
        else if (a < num)
        {
            cout << "猜测过小" << endl;
        }
        else
        {
            cout << "恭喜您猜对了" << endl;
            break;
        }
    }

    system("pause");
    return 0;

}
阅读 8.1k
3 个回答
int main()
{
    srand((unsigned int)time(NULL));
    int num = rand() % 100 + 1;
    cout << num << endl;

    int a = 0;
    int ti = 0;
    int ti2 = 0;
    
    while (a != num && ti2 < 4)
    {
        ti2 = ti++;
        cin >> a;
        if (a > num)
        {
            cout << "猜测过大" << endl;
        }
        else if (a < num)
        {
            cout << "猜测过小" << endl;
        }
        else
        {
            cout << "恭喜您猜对了" << endl;
            break;
        }
    }

    system("pause");
    return 0;

}

在while块外声明一个整型变量作为计数器, while循环每次执行后对该计数器+1, 直到超过阈值时break退出.

这和 while 语句没关系 >5次不显示失败 这是if语句 加入到游戏开始之前(也就是你这的while语句之前给 return出去)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题