随机数生成器以升序输出数字

时间:2015-02-20 19:36:14

标签: c++ random integer srand time.h

首先,我是一名早期初学程序员,并希望得到一些帮助。

我编写了以下代码,这些代码来自我测试过的代码:

  • 5个随机数:1和39 // num1gen到num5gen - 例如A组
  • 1个随机数:1和14 // Thunderball - 例如B组

我只想cout<< A组按升序排列,我不确定添加此功能需要哪些编码。

我仍然需要生成的随机数放在下面显示的整数名称中:

  • num1gen = 12
  • num2gen = 24
  • num3gen = 3
  • num4gen = 5
  • num5gen = 32
  • Thunderball = 12

错误:ISO C ++禁止减速' i'在第16行没有类型[-fpremissive]。

到目前为止,在以下用户的帮助下,代码已经完成了:

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <algorithm>

using namespace std;

int main()

{

 srand(time(NULL));

std::vector<int> numA(5);
srand( time(NULL) );
for( auto i(0); i < numA.size(); ++i )    //line no 16 error
numA[i] = (rand()%49+1);

  int num1gen=(rand()%49+1);    // this is the value of ball no.1
  int num2gen=(rand()%49+1);    // this is the value of ball no.2
  int num3gen=(rand()%49+1);    // this is the value of ball no.3
  int num4gen=(rand()%49+1);    // this is the value of ball no.4
  int num5gen=(rand()%49+1);    // this is the value of ball no.5


    std::sort(numA.begin(), numA.end());

num1gen=numA[0];
num2gen=numA[1];
num3gen=numA[2];
num4gen=numA[3];
num5gen=numA[4];

 cout<<num1gen<< ", "<<num2gen<< ", "<<num3gen<< ", "<<num4gen<< ", "
 <<num5gen<< " ";"

    return 0;
  }

2 个答案:

答案 0 :(得分:2)

如果您在A中创建数字作为向量,则会有一个带排序的算法标题,所以类似于:

#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numA(5);
    srand( time(NULL) );
    for( unsigned int i(0); i < numA.size(); ++i )
        numA[i] = (rand()%49+1);
//After you create the vector and do your test that they're not equal
    std::sort(numA.begin(), numA.end());

    return 0;
}

std::sort()标头中包含#include <algorithm>

答案 1 :(得分:1)

 #include <random>
 #include <vector>
 #include <algorithm>
 #include <numeric>

 int main()
{
 std::vector<unsigned> balls(39);
 std::iota(balls.begin(), balls.end(), 1);
 std::shuffle (foo.begin(), foo.end(), std::mt19937(std::random_devic{}()));
 balls.resize(5);
 std::sort(balls.begin(), balls.end());
 std::cout << "Balls: "
 std::copy(balls.begin(), balls.end(), std::ostream_iterator<unsigned>{std::cout," "})
}