How to set rand command, an integer from 3 to 50 (inclusive), but save it as a decimal number

What have you tried so far?

Off the top of my head, I'd probably use two variables.
Call rand() and assign its output to an integer variable, say, temp_int.
Do a modulus operation on this variable: temp_int %= 50;
That should keep the variable's value to 50 or less.
Do a check to see if variable's value under 3; if so, add 3.
Assign this variable's value to a variable of type float.

There's probably a shorter, more elegant, way to do this, but even an awkward way like this should get you started.

Please post code so we know how you progress.

Here's an example that may help:

#include <stdio.h>
#include <stdlib.h>

double uniform_deviate(int seed)
    return seed * (1.0 / (RAND_MAX + 1.0));

int main(void)
    int lo = 3, hi = 50;

    for (int i = 0; i < 1000; i++) {
        double r = lo + uniform_deviate(rand()) * (hi - lo);
        int block = i + 1;

        printf("%f ", r);

        if ((block % 10) == 0) {

        if ((block % 100) == 0) {
            getchar(); // Pause

    return 0;

The trick is in the uniform_deviate function that takes the seed value and reduces it to a floating point value between 0 and 1. You can then multiply that accordingly to get a floating point value in the range you want.

The benefit is that you don't lose precision on the floating point value due to rand being strictly integer based, and I'd like to think it's an elegant solution to boot. ;)

This article has been dead for over six months. Start a new discussion instead.