/* Include lib */
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
/* Define */
#define MAX_LOOP 100
/* API generate positive random float number */
/* NOTE: not care a > b & vice versa */
double positive_float_rand_in_range(double pos_a, double pos_b)
{
double pos_start, pos_end, float_rand;
/* FIXME: Check wrong input a, b */
/* Random number with in [start, end] */
if (pos_a >= pos_b) {
pos_start = pos_b;
pos_end = pos_a;
} else {
pos_start = pos_a;
pos_end = pos_b;
}
/*
* Random float in [a, b] = a + random float in [0, b - a], with c = b - a.
* Random float in [0, c] = c * random float in [0, 1].
* Random float in [0, 1] = random int / RAND_MAX
*/
float_rand = pos_start + (pos_end - pos_start) * ((double)rand() / RAND_MAX);
return float_rand;
}
/* API generate random float number (positive or negative) */
/* NOTE: not care a > b & vice versa */
double float_rand_in_range(double a, double b)
{
/* Process input to generate random float in positive range, then process output */
if (a < 0 && b < 0) {
return -positive_float_rand_in_range(-a, -b);
} else if (a < 0 && b > 0) {
/* Random float in [-x, y] = random float in [0, y + x] - x, with x positive */
return positive_float_rand_in_range(-a, b) - (-a);
} else { /* a > 0 && b > 0 */
return positive_float_rand_in_range(a, b);
}
}
/* Main func interract with user */
int main(void)
{
int sel, i;
double a, b;
while (1) {
printf("\n\nSelection:\n");
printf("0 : Input range to generate random float\n");
printf("1 : Exit\n");
printf("Select: ");
scanf("%d", &sel);
switch (sel) {
case 0:
printf("Input a: ");
scanf("%lf", &a);
printf("Input b: ");
scanf("%lf", &b);
for (i = 0; i < MAX_LOOP; i++)
printf("=> Random: %lf\n", positive_float_rand_in_range(a, b));
break;
case 1:
return 0;
default:
printf("Option not available\n");
break;
}
}
return -1;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: