The rand()
function generates pseudo-random integers with values between 0
and RAND_MAX
inclusive. Your formula involves integer operations thus produces integer values. Your goal can be achieved this way:
double money;
money = 10.0 + (double)rand() * 30.0 / (double)RAND_MAX;
printf("Show amount: %.2f ", money);
This will generate peudo-random floating point values in the target range. It may not fit your purpose because these values will not a be a round number of cents. Indeed IEEE floats or doubles cannot precisely represent all exact numbers of cents. You will come closer by using this method:
money = 10.0 + (double)(rand() % 3001) / 100.0;
values will be as close as possible to exact numbers of cents, but a more accurate and simpler method is just to compute with integer amounts of cents and convert to currency only at print time:
int money = 1000 + rand() % (4000 - 1000 + 1);
printf("Show amount: %d.02d", money / 100, money % 100);
If money
can be negative, extra care must be taken to print negative values:
if (money < 0) {
printf("Show amount: -%u.02u", -money / 100, -money % 100);
} else {
printf("Show amount: %d.02d", money / 100, money % 100);
}
If you decide to use floating point values, use the double
type.
Some casts in the above examples are not strictly necessary as promotion rules will make them implicit, I wrote them on purpose for clarity.