Created
June 2, 2013 18:18
-
-
Save 0x00b1/5694347 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Write a C function whose return value is an integer between one and five: | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
int sample(int minimum, int maximum) | |
{ | |
int random = rand(); | |
int range = maximum - minimum; | |
if (RAND_MAX == random) | |
{ | |
return sample(minimum, maximum); | |
} | |
if (random < RAND_MAX - (RAND_MAX % range)) | |
{ | |
return minimum + random / (RAND_MAX / range); | |
} | |
else | |
{ | |
return sample(minimum, maximum); | |
} | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
srand(time(NULL)); | |
printf("%d", sample(1, 5)); | |
return 0; | |
} | |
/* | |
Write a C function whose return value is an integer between one and seven: | |
int main(int argc, const char * argv[]) | |
{ | |
srand(time(NULL)); | |
printf("%d", sample(1, 7)); | |
return 0; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment