【问题标题】:if statement in for loop (random number generator)for 循环中的 if 语句(随机数生成器)
【发布时间】:2019-01-04 19:06:12
【问题描述】:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
unsigned seed;
cout << "Input a whole number between 0 and 65535 to\n initialize the random number generator: ";
cin >> seed;
srand(seed);

int number;
number = rand();

int count;
for (count = 1; count <= 20; count++)
{

    if (number >= 1 && number <= 100)
    {
        cout << number << endl;
        number = rand();
    }
    else
    {
        number = rand();
        --count;
    }

}
return 0;
}

我试图编写一个随机数生成器,它打印出 20 个介于 1 和 100 之间的随机数,包括 1 和 100。在我在 else 语句 (--count) 中减少“count”之后,现在一切正常。没有那个“--count”,程序只输出一个数字或根本不输出数字。如果 if 语句初始化 rand() 函数以在每个循环后生成一个新数字,为什么它只输出一个数字?谁能向我解释为什么我必须在这个 else 语句中加上 --count ?减少“计数”更像是猜测,而不是知道原因。即使它会生成一个超过 100 的数字,它也必须一次又一次地生成它,直到它符合情况为止?

【问题讨论】:

  • 您必须将--count 放入else,因为当随机数不在[1, 100] 范围内时,您不想增加count。所以在else 块你做--count 和循环迭代你做++count 等式变成((count - 1) + 1) = count 因此count 在数字不在范围内时不会改变 [1, 100]
  • 谢谢你的回答我现在明白了!不幸的是,我无法投票,因为我的声誉低于 15。

标签: random numbers generator


【解决方案1】:

在您的初始代码中,如果该值超出了您想要的范围 (1-100),它仍会在您的 for 循环中增加计数,但不会打印任何内容,因为该数字超出了范围。你需要 --count;为了从本质上告诉您的 for 循环“数字超出范围,因此不要计算该迭代并重试。”

【讨论】:

  • 好的,我现在明白了。但是为什么程序总是打印一个数字或不打印数字呢?根据您的说法,它有时应该打印 2、5、1、4 0 数字等...还是不打印?
  • 谢谢你的回答我现在明白了!不幸的是,我无法投票,因为我的声誉低于 15。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 2016-06-16
  • 2019-06-09
相关资源
最近更新 更多