Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
rand in a closed interval on the ints
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Frank Silvermann, post: 2468586"] /* rand_in_range.c : contributors: usual suspects in clc */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define SWAP(m, n) (tmp = (m), (m) = (n), (n) = tmp) #define ITERATIONS 100 int rand_in_range(int, int); int main(void) { int tja, i , j, m, n; /* all declarations in main need to be north of here */ /* seed timer */ srand(time(NULL)); /* call rand and count returns */ j = 0; m = 8; n = 3; printf("range is [%d, %d]\n", m, n); for (i=0; i < ITERATIONS; i++) { tja = rand_in_range(m, n); if (i < 10) printf("return is %d\n", tja); j += tja; } printf("total is %d\n", j); return 0; } int rand_in_range(int m, int n) { /*seed srand in main */ /* [m, n] is range */ int t, top, diff, p, tmp; if (m == n) return m; if (m > n) SWAP(m, n); diff = n - m; top = RAND_MAX - (RAND_MAX % (diff + 1) + 1); /* control */ do t = rand(); while (t > top); p = t % (diff + 1) ; p = p + m; return p; } /* end source */ I think this is right. frank [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
rand in a closed interval on the ints
Top