i looked at the tutorials of generating random numbers and it was too hard to understand.I just want one random number to be generated at the start of the program between 1 and 100 inclusive could anyone help?
i looked at the tutorials of generating random numbers and it was too hard to understand.I just want one random number to be generated at the start of the program between 1 and 100 inclusive could anyone help?
Or something along the lines of this.Code:srand(time(NULL)); int num = (rand() % 99) + 1;
Here's the main part of that code:
[edit]Code:#include <ctime> int main (void) { srand (time(NULL)); int number; //number = (rand() % (max - min + 1) + min); //max = 100, min = 1 //just remember - rand () % some_int will return a value //between 0 and (some_int - 1) number = (rand() % (100 - 1 + 1) + min); return 0; }
Desolation's code was fine actually
[/edit]
No No's:
fflush (stdin); gets (); void main ();
Goodies:
Example of fgets (); The FAQ, C/C++ Reference
My Gear:
OS - Windows XP
IDE - MS Visual C++ 2008 Express Edition
ASCII stupid question, get a stupid ANSI
My compiler complains about this code but whatever, it should work.Code:class RandomNumber { public: RandomNumber() : min(0), max(1) { } // other constructors inline operator int() { return ((rand() % (max - min)) + min); } public: int min, max; };
Edit: Usage.Code:RandomNumber randy; int rand_num = randy;
Last edited by Desolation; 05-27-2006 at 11:44 PM.
why should min and max both be zero if we use a constructor with no arguments? I'm sorry it just makes no sense. If you do that than rand() gets devided by zero?! Never even risk deviding by zero!
I assumed that is was obvious you would set both min and max... You can set max to 1 to get rid of the problem.
You're abusing OOP here's a function which should do the same thing:
Guaranteed idiotproof!
UsageCode:int randnum(long min = 0, long max = RAND_MAX) { min %= RAND_MAX + 1; max %= RAND_MAX + 1; if(min == max) { return min; } if(min > max) { std::swap(min, max); } return rand() % ((max - min + 1)?(max - min + 1):RAND_MAX) + min; }
Code:randnum(1, 5); //1 ~ 5 randnum(5, -5); //-5 ~ 0 ~ 5 randnum(-70, -4); //-70 ~ -4 randnum(6, 6); //6
Code:#include <stdio.h> void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){ puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9 /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i] ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][ t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}