gpt4 book ai didi

C++骰子程序难点

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:53 25 4
gpt4 key购买 nike

问题:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com