Random Number Game (The random part)

Jun 30, 2008 at 5:27am
Hey! New to the forums here and new to C++ in general. I am trying to make a random number game and I need some help. :\ I need to make the random numbers be between 1 and 20, not just completely random numbers. Here is my code.

[code=cpp]//declaring header files
#include "stdafx.h"
#include <iostream>

//using the std namespace for easier writing
using namespace std;

//initializing the main program
int main()
//main code
{
//display weclome message
cout << "Hello, and welcome number adding system!\n\n";
//press any key to continue and skip a line
cin.get( );
cout << endl;
//loop the random number
int loop_int = 0;
while(loop_int < 1)
{
int rand_int = rand();
cout << rand_int << endl;

}



}[/code]
Jun 30, 2008 at 6:02am
Check this out cplusplus.com/reference/clibrary/cstdlib/rand.html
Last edited on Jun 30, 2008 at 4:39pm
Jun 30, 2008 at 9:20am
Take look at the documentation for rand()
http://www.cplusplus.com/reference/clibrary/cstdlib/rand.html

If you want to have random numbers between a specific range you can use rand_value = (rand() % range) + offset.
For your example range would be 20 and offset 1 (the rand()%range produce numbers from 0 to range-1).

You will find out that the random numbers are always the same when you run your program.For that reason you have to use the srand to set a really random start point. Here is the documentation for srand from microsoft:
http://msdn.microsoft.com/en-us/library/aa272944(VS.60).aspx
Last edited on Jun 30, 2008 at 8:12pm
Jun 30, 2008 at 7:28pm
I entered that piece of code but I get an error when I try to compile:

1>c:\documents and settings\brad\my documents\visual studio 2008\projects\consoleproject\consoleproject\consoleproject.cpp(22) : error C2296: '%' : illegal, left operand has type 'int (__cdecl *)(void)' Any suggestions?
Jun 30, 2008 at 8:11pm
Did you add the parenthesis after the rand? "rand()"
I'm sorry, i forgot it in my code above... I edited it and corrected it.
Last edited on Jun 30, 2008 at 8:12pm
Jun 30, 2008 at 8:12pm
while ( loop_int < 1 )
{
int rand_int = rand() % 20;
cout << rand_int << endl;
}
Jun 30, 2008 at 8:23pm
>> Did you add the parenthesis after the rand? "rand()"

Ahh thanks, that was the issue. Thanks a alot!
Topic archived. No new replies allowed.