Rand() doesn't really work?

The rand() function is always returning 41 for me. This obviously makes the function pointless. Any ideas as to why this is happening?
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main()
{
int x = rand();
cout << x;
system("pause");
return 0;
}
#include <ctime> and call strand(time(0)) at the beginning of 'main'
i got this for random :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int random(int);
int main()
{
  srand(time(0));
  int n,max,o,chance;
  cout << "Put a random number:\n";
  cin >> max;
  o=random(max); 
blablabla
}
int random(int o) {
  return rand()%o;
  
}
Last edited on
I think would better if you returned rand()%o+1
Thanks! this really helped me. I'm making a random sentence generator!
I just tested some random things and it worked with this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int choose = rand()%10;

switch (choose)
{
case 0: cout << "This is the lowest!" << "\n"; break;
case 1: cout << "Jackal!" << "\n"; break;
case 2: cout << "Hey! this is random!" << "\n"; break;
case 3: cout << "This is a sentence." << "\n"; break;
case 4: cout << "Dog" << "\n"; break;
case 5: cout << "Right in the middle!" << "\n"; break;
case 6: cout << "Yeah" << "\n"; break;
case 7: cout << "Nope" << "\n"; break;
case 8: cout << "Sea monkeys!" << "\n"; break;
case 9: cout << "You found the nine!" << "\n"; break;
case 10: cout << "This is the highest!" << "\n"; break;
}

system("pause");
return 0;
}
Last edited on
nice work Mashed! I show what i had to do in a program, pretty simple though...

This is the function:

// Para calcular valores aleatorios entre 0 y 1.
double Aplicacion::aleatoria()
{
return static_cast<double>((rand()%10000)/10000.0) + 0.0001;
}

on main I use this srand:

srand(static_cast<unsigned>(time(NULL)));

CalculaPi dardo; // El Objecto dardo es creado.
Aplicacion imprime; // El Objeto imprime es creado.

call

for (int i = 0; i < corre; i++)
{
valX = imprime.aleatoria();
valY = imprime.aleatoria();

dardo.radio(valX, valY);

if( i % veces == 0)
{
imprime.calculoPrint(dardo);

imprime.detenerTiempo(tiempo);
}

}

This is not the whole program, its divided in 5 archive to increase readability and management.

Just showing how I use the srand and stuff... :)
Nice! thanks for the addition!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

Try This Pgm ,

It will generate different random nos ...

void main(void)
{
int i;

srand(time(NULL));

i = rand();

printf ("Random number is %d\n", i);

printf ("Range between 0 to %d\n", RAND_MAX);

getch();
}

Thanks,
RK
Topic archived. No new replies allowed.