C++骰子程序难点

标签 c++ loops random

问题:

Repeatedly roll 3 dice until doubles are rolled (any two are the same). Show the values each time and afterwards state how many tries it took to get doubles.

我的代码:

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main ()
{
    srand (time(NULL));
    int j=1;
    int i=0;
    int a;
    int b;

    do
    {
        int a=(rand ()%6+1);
        int b=(rand ()%6+1);

        cout<<a<<" and "<<b<<endl<<endl;
        j++;
    }
    while (a!=b);

    cout<<"They are the same!"<<endl<<endl;
    cout<<"It took "<<j<<" tries.";

    return 0;
}

问题:

循环不会停止。即使 a 和 b 相同,程序也不会停止。

最佳答案

您正在 do ... while 循环中重新定义 ab。删除第二个 ab 定义之前的 int,您可以在其中将随机值分配给变量,它会起作用。

关于C++骰子程序难点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484646/

相关文章:

c++ - 如何在 C++ 中为 SQLite 模拟 ADO 的编辑/更新机制?

php - MySQL 和 PHP - 每个?

python - 在 Python 中随机交错 2 个数组

C++,()运算符重载,它的工作是什么

c++ - 在 const 成员初始化之前使用,这是 gcc 和 clang 的预期行为吗?

c# - 自定义存档格式文件读取

javascript - 只要求用户正确答案 5 次的简单 JavaScript 函数?

python - 如何使用 pandas 中的 apply 函数实现此 iterrow 情况?

mysql - 使用max、group by、临时表和随机行选择的mysql查询结果的性能

ruby - 为什么我要为 Array#shuffle 使用自定义 RNG?