Author Topic: Help generating random numbers (C::B)  (Read 1297 times)

Gabbe

  • Guest
Help generating random numbers (C::B)
« on: 11 October 2010, 17:34:21 »
Code: [Select]
#include <iostream>
#include <cmath>
#include <cstdlib>

int main(){
    using namespace std;

    double y;
    y = rand();

    cout << y << endl;

    cin.get();
    return 0;
}

code in c++, sumposed to generate a random number, but it won`t :S

BTW system("pause"); replaced with cin.get(); doesnt work either :(
« Last Edit: 11 October 2010, 17:37:21 by Gabbe »

Yggdrasil

  • GAE Team
  • Ornithopter
  • ********
  • Posts: 408
    • View Profile
Re: Help generating random numbers (C::B)
« Reply #1 on: 11 October 2010, 18:02:26 »
You need to initialize the pseudo-random generator with srand, mostly srand(time(NULL)).

See:
http://cplusplus.com/reference/clibrary/cstdlib/rand/

Gabbe

  • Guest
Re: Help generating random numbers (C::B)
« Reply #2 on: 12 October 2010, 11:26:14 »
I think i might have goten a C::B related problem, I tried to run a new program that were supposed to do 5 * 5 * 5.

Code: [Select]
#include <iostream>
#include <cmath>
#include <cstdlib>

int main(){
    using namespace std;

    double rainbow;
    rainbow = pow(5,3);

    cout << rainbow << endl;

    cin.get();
    return 0;
}

No output when it tried to build, but the error log said:

Quote
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 0 warnings



-------------- Build: Release in begining functions ---------------

Compiling: main.cpp
mingw32-g++.exe: installation problem, cannot exec `cc1plus': No such file or directory
Process terminated with status 1 (0 minutes, 0 seconds)
0 errors, 0 warnings
« Last Edit: 12 October 2010, 11:33:51 by Gabbe »

Omega

  • MegaGlest Team
  • Dragon
  • ********
  • Posts: 6,167
  • Professional bug writer
    • View Profile
    • Personal site
Re: Help generating random numbers (C::B)
« Reply #3 on: 12 October 2010, 18:01:54 »
Basically, you have to seed the random numbers. Otherwise its the same "random" number every time. Yggrdasil's link might help.
Edit the MegaGlest wiki: http://docs.megaglest.org/

My personal projects: http://github.com/KatrinaHoffert

Gabbe

  • Guest
Re: Help generating random numbers (C::B)
« Reply #4 on: 12 October 2010, 19:11:32 »
Not anything i write in C::B works any :(

Omega

  • MegaGlest Team
  • Dragon
  • ********
  • Posts: 6,167
  • Professional bug writer
    • View Profile
    • Personal site
Re: Help generating random numbers (C::B)
« Reply #5 on: 13 October 2010, 01:48:04 »
C::B is code blocks, right? Code doesn't depend on the compiler really. You're simply doing it wrong.
Edit the MegaGlest wiki: http://docs.megaglest.org/

My personal projects: http://github.com/KatrinaHoffert

Gabbe

  • Guest
Re: Help generating random numbers (C::B)
« Reply #6 on: 13 October 2010, 08:42:13 »
Build&run?

Yeah, "Code::Blocks"

Dev c++ works..
« Last Edit: 13 October 2010, 08:45:14 by Gabbe »