问题:
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
循环中重新定义 a
和 b
。删除第二个 a
和 b
定义之前的 int
,您可以在其中将随机值分配给变量,它会起作用。
关于C++骰子程序难点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484646/