使用C ++生成介于-30和30之间的数字

时间:2015-09-08 19:53:14

标签: c++

我希望在-30到30之间生成数字。

我已经在Generating random integer from a range中尝试了解决方案,它给了我这些结果:

111875657664
151875657664
211875657664
-41875657664
-151875657664
171875657664
-201875657664
-131875657664
-301875657664
-271875657664

这是我的功能:

int Random::genRandom() {
    int rnd;
    rnd = (rand()%61)-30;
    return rnd;
}

这是主要的源文件:

#include "Random.h"
#include <iostream>
using namespace std;

int main() {
    Random random;
    int randomas;
    for(int i=0; i<10; i++) {
        randomas = random.genRandom();
        cout << randomas << "\n";
    }
    return 0;
}

我该怎么办?

3 个答案:

答案 0 :(得分:2)

试试这个:

srand (time(NULL));
for(int i = 0;  i < 10; i++)
{
    int rnd;
    rnd = rand() % (60) - 30;

    cout << rnd << std::endl;
}

工作示例here

答案 1 :(得分:2)

这没有解决OP的奇怪数字问题(我似乎无法重现),只是为了解决这个问题。 C ++ 11和更好的方法提供了许多不同的方法来解决rand糟糕的问题。

我,欢迎我们new random number generating overlords

#include <iostream>
#include <random>

int main()
{
    std::random_device device;
    // build a random number generator for seeding
    std::default_random_engine engine(device()); 
    // nothing fancy. Assuming the compiler implementors know what they are doing
    // seeding it with a nice random number from above.
    std::uniform_int_distribution<int> distribution(-30, 30);
    // generate uniformly distributed numbers from -30 to 30

    int randomas;
    for(int i=0; i<10; i++) {
        randomas = distribution(engine); // Bless me with a number, divine masters!
        std::cout << randomas << "\n"; // Witness the number all shiny and chrome!
    }
    return 0;
}

答案 2 :(得分:1)

试试这段代码。它是线性同余生成器在您的问题中的应用。发电机具有很好的性能。

$('.header-nav li:nth-child(2)').hover(
    function() {
      $( this ).html('<div class="new-messages-f">77</div><a href="">Account</a>'); // Replaced
    },function() {
      $( this ).html('<div class="new-messages-f">89</div><a href="">Ac</a>'); // Original
    });
相关问题