编写程序生成1000个0-49范围内的随机整数.(c++)

Write a program that will generate 1000 random integers in the range 0-49. (C++)

本文关键字:整数 随机 c++ 范围内 程序生成 1000个 0-49      更新时间:2023-10-16

我已经看了这里问的其他问题,但不能找到我需要的。

我有这个问题;

编写程序生成1000个0-49范围内的随机整数。它应该计数并报告在0-24范围内有多少,在25-49范围内有多少。

这是目前为止我写的;

#include<iostream>
#include<ctime>   //For time()
#include<cstdlib> //For rand() and srand()

using namespace std;
int main()
{
    int x;
    int counter = 0;
    int y = 0;
    int z = 0;
    srand(time(NULL));
    for (counter = 0; counter < 1000; counter++) {
    {
        x = rand() % 49 + 1;
        if (x >= 0 && x <= 24)
        {
            y++;
        }
        else if (x > 24 && x <= 49)
        {
            z++;
        }
    }
    cout << "Number of numbers between 0-24: " << y << endl;
    cout << "Number of numbers between 25-49: " << z << endl;
    system("pause");
    return 0;
   }
 }

它循环一次,但我不明白如何让它循环一遍又一遍,直到1000个数字已经生成和分类。

我对c++很陌生,所以有人能解释一下如何让这个循环吗?我错过了什么非常明显的东西吗?

你在for循环中有太多的花括号。正因为如此,你的returncoutfor循环中发生。它得到一个数字,打印出来,然后在它返回之前返回。试试这个:

#include<iostream>
#include<ctime>   //For time()
#include<cstdlib> //For rand() and srand()
using namespace std;
int main()
{    
    srand(time(NULL));
    for (counter = 0; counter < 1000; counter++)
    {
        int x;            //See Note #3 Below
        int counter = 0;
        int y = 0;
        int z = 0;
        x = rand() % 50;  //See Note #1 Below
        if (x < 25)       //See Note #2 Below
        {
            y++;
        }
        else
        {
            z++;
        }
    }
    cout << "Number of numbers between 0-24: " << y << endl;
    cout << "Number of numbers between 25-49: " << z << endl;
    system("pause");
    return 0;   
 }

关于代码的3个注意事项:

  1. 你的随机数生成器只得到数字1-49,而不是0-49。
  2. 你真的不需要这样构造if语句。你所要做的就是说,"如果小于25,把它放在一个桶里,否则,把它放在另一个桶里。"
  3. 你可能想在变量被使用的范围内声明变量。在本例中,是您的for循环。