user2699298 user2699298 - 10 months ago 63
C Question

How to calculate float in C?

I need to generate a random number for seconds and then take the seconds and calculate how many minutes and hours are those seconds. So, I generate a number first using rand(), but it seems kinda weird, every time I run the program, the random number (previous) just increases by 3. Yes, it's random, but still only increases by 3 every next run. I'd like to make it more random if possible.

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

int main()
long sekundi;
sekundi = rand();
double minuti,casovi;
casovi = (sekundi / 3600);
minuti = (sekundi / 60);
printf("%d \n",sekundi);
printf("%4.2f \n",casovi);
printf("%4.2f \n",minuti);

return 0;

That's my code, I'm new to C please excuse my formatting and everything. It doesn't seem to calculate the hours and minutes correctly, it does correct for the first number and then adds x,00 after the number without correct decimal numbers.

Answer Source

I suspect that, when you initialize your generator with two seeds that are close to each other numerically, the first numbers in the generated sequence are also likely to be close numerically. One would hope, however, that the sequences will diverge very quickly after that.

In my environment discarding the very first number seems to help:

long sekundi;
rand(); // <<<<< THIS
sekundi = rand();

Of course, if you run the code twice within the same second, the generator will still be seeded with exactly the same value and you'd get exactly the same output both times. If that an issue you should probably use a higher-resolution timer to generate the seed.

As to the other aspect of your question, it seems likely that you want to use floating-point, and not integer, division:

casovi = (sekundi / 3600.);
minuti = (sekundi / 60.);

(Note the added . at the end of the numeric literals.)