【问题标题】:C++ Dice Program DifficultiesC++ 骰子程序的难点
【发布时间】:2013-10-29 08:41:42
【问题描述】:

问题:

反复掷 3 个骰子,直到掷出双倍(任何两个都是 相同的)。每次显示值,然后说明尝试次数 需要双打。

我的代码:

#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 相同,程序也不会停止。

【问题讨论】:

    标签: c++ loops random


    【解决方案1】:

    您正在循环内声明新变量,这些变量会影响您在循环外声明的 a 和 b。 while (a != b) 正在查看外部的,但你并没有改变那些。

    去掉int a = (rand() % 6) + 1上的int

    如果您使用的是 gcc/g++,您可能会在编译器中使用 -Wshadow 标志为自己省点麻烦。对于其他编译器,我不知道选项是什么,但可能有一个。至少这会在编译时而不是运行时告诉您问题。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-09-05
        • 2014-04-21
        • 2012-03-18
        • 1970-01-01
        • 2012-02-29
        • 2014-08-25
        • 1970-01-01
        • 1970-01-01
        • 2017-04-09
        相关资源
        最近更新 更多