简体   繁体   English

如何生成无限随机数的骰子直到它们相等?

[英]How do I generate infinite random numbers of pair of dice until they are equal?

I'm trying to simulate a program that will roll a pair of dice and it will generate the results until the variables are equal, however I can't figure this out. 我正在尝试模拟一个将掷出一对骰子的程序,它将生成结果,直到变量相等,但我无法弄清楚这一点。

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main() { 
    const int MIN_VALUE = 1;
    const int MAX_VALUE = 6;

    int die1,die2;

    unsigned seed = time(0);
    srand(seed);

    die1 = (rand()%(MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
    die2 = (rand()%(MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;

    while(die1 == die2); {
        die1 = (rand()%(MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
        die2 = (rand()%(MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;

        cout<<"Value of die 1  is"<<die1<<endl;
        cout<<"Value of die 2 is" <<die2<<endl;
        cout<<endl;
    }
    return 0;
}

A couple of issues here: 这里有几个问题:

  • The ; ; at the end of line where the while statement begins means that the while is not connected to the block of code below. while语句开始的行的末尾表示while未连接到下面的代码块。 Remove it. 去掉它。 (if die1 value equals die2 at the beginning itself, you will have an infinite loop there itself.) (如果die1值在开头本身等于die2 ,那么你自己就会有一个无限循环。)

  • The condition to check is die1 != die2 because you want to roll the dice as long as they are not equal. 要检查的条件是die1 != die2因为你想要掷骰子,只要它们不相等。

See Demo . 演示

There are two mistakes in while(die1 == die2); while(die1 == die2);有两个错误while(die1 == die2); .

The == makes the loop continue while the values are equal, but you want the opposite. ==使循环继续,而值相等,但你想要相反。
The condition could be endless if the two dice start off equal (because the rerolling never happens, see below). 如果两个骰子开始相等,则情况可能是无穷无尽的(因为重新滚动从未发生过,见下文)。
Otherwise it will be "never". 否则它将是“永远”。
The semicolon will prevent the while from having any effect on the following {} , it will be executed exactly once, in case the loop is not endless, otherwise never. 分号将阻止while对以下{}产生任何影响,它将被执行一次,以防循环不是无限的,否则永远不会。

So change to: 所以改为:

while(die1 != die2)
{
    /* reroll */
}

In case you want to make your code easier to maintain and read, investigate about do {} while(); 如果您想让代码更易于维护和阅读,请调查do {} while(); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM