On 25.02.2019 08:32,
arief...@gmail.com wrote:
> hi guys
> when i run my program, result stack in 37, i want result of this
> script as below will be random, how to get the best script
[Reformatted with AStyle:]
> #include <iostream>
> //using namespace std
> #include <stdio.h>
> #include <stdlib.h>
>
> int main() {
> int c, a;
> int n;
> a = rand()% 50 +1;
> printf("value a is %d \n",a);
>
> for(c =1; c <= a; c++) {
> n = rand()% 50 + 1;
> //n = rand();
> printf("value : %d \n",n);
> return n;
> }
> printf("value of n : %d \n",n);
> if (n > 50) {
> printf(" lowest : %d",n);
> }
> else printf("highest : %d",n);
> return 0;
> }
If you want different pseudo-random sequences then you have to provide a
/seed/ value that's different in each run of the program.
For the machinery you're using you pass that seed value to `srand`, but
where to get a varying seed?
One portable possibility is to use `time`, but note that it doesn't vary
fast enough to guarantee different values in close runs of the program.
Another portable possibility is to use the modern C++ random generation
facilities just for this, `std::random_device`. Declare such an object.
It's callable, so you just call it (like a function) to get the random
seed value. Note: at least as version 8.2.0 g++ wasn't quite up to date
in its implementation; if it doesn't work with g++ you can define
`_GLIBCXX_USE_RANDOM_TR1` globally in the build.
Of course, using the modern facilities for a random seed, you might
almost just as well use them also for the random number generation. It's
slightly more complex code, though. Unless you write a reusable wrapper.
Cheers!,
- Alf