Reputation: 81
This is my function
int nepresnost_N2(int S){
int N2, N2_1, N2_2;
N2_1 = -S/10;
N2_2 = S/10;
N2 = rand() % (N2_2 + 1 - N2_1) + N2_1;
printf("%i", N2);
}
I dont know how to make conditions for (without 0). Any ideas, thanks :)
Upvotes: 2
Views: 1063
Reputation: 726539
Since your range has both a negative and a positive side, going from -s
to +s
, you can shorten the positive part of the range by 1, then add 1 in case when the generated value is non-negative:
N2_1 = -S/10;
N2_2 = S/10-1; // Shrink by one
N2 = rand() % (N2_2 + 1 - N2_1) + N2_1;
if (N2 >= 0) { // Correct for zero
N2++;
}
Alternatively you could check the result for zero, and generate a new number if necessary:
int nepresnostNoZero(int S) {
int res;
do {
res = nepresnost_N2(S);
} while (res == 0);
return res;
}
Upvotes: 5
Reputation: 234685
If you want drawings to be in the range [a, b]
excluding zero, then generate a random number in [a, b - 1]
and add 1 to it if the returned value is non-negative.
That will have superior statistical properties to sampling and rejecting 0
values.
Upvotes: 5