Thursday, 15 September 2011

generate random number in a range c++ -



generate random number in a range c++ -

this question has reply here:

how modulus , rand() work? 4 answers

i'm using ncurses library build game. i'm having problem generating right random numbers. while loop below needs maintain generating random numbers until between 1 , 45(this y-axis limits on standard screen). can't figure out i'm doing wrong because while loop status looks fine me. problem while loop starts running infinitely. im not doing printing generated numbers @ end want see right numbers generated. can please help me problem? next int main.

int main() { int r,c,x=0; initscr(); raw(); keypad(stdscr, true); noecho(); //mvprintw(22,45,"<"); getmaxyx(stdscr,r,c); int n,n2 = 0; while((n<1)||(n>45)){ srand (time(null)); n = rand(); srand (time(null)); n2 = rand(); } mvprintw(4,10,"first random number: %d\n", n); mvprintw(5,10,"second random number: %d\n", n2); getch(); endwin(); homecoming 0; }

you want phone call srand once @ start of things , utilize modulus bring rand results range, like:

srand(time(null)); n = rand() % 45 + 1; n2 = rand() % 45 + 1;

c++ c random

No comments:

Post a Comment