Why is this integer division giving 0?

Can someone tell me why the following code prints 0 to the marked line?

Everything seems to be correct, but then when I try to get the result closer to the end, it gives me 0 every time.

 #include <stdio.h> int main() { // Gather time-lapse variables int frameRate, totalLengthSecs; printf("How many frames per second: "); scanf("%i", &frameRate); printf("--> %i frames confirmed.", frameRate); printf("\nDesired length of time-lapse [secs]: "); scanf("%i", &totalLengthSecs); printf("--> %i seconds confirmed.", totalLengthSecs); int totalFrames = frameRate * totalLengthSecs; printf("\nYou need %i frames.", totalFrames); // Time-lapse interval calculation int timeLapseInterval = totalLengthSecs / totalFrames; printf("\n\n%i", timeLapseInterval); // <-- this prints 0 return 0; } 
+4
source share
4 answers

In short: integer division truncates

You need the following:

 double timeLapseInterval = (double) totalLengthSecs / (double)totalFrames; printf("\ntimeLapseInterval : %f \n", timeLapseInterval); 
+4
source

Performing integer math.

Math between two integers will produce an integer. And the result will be rounded to zero.

This line:

 totalLengthSecs / totalFrames; 

Probably the result is between 0 and 1 . And rounding to 0

+3
source

You print integers and therefore round the value.

timeLapseInterval / totalFrames will be (1 / frameRate) , which will be <1 if frameRate is not 1 (or 0, in which case you divide the error by 0)

+1
source

When you divide 2 numbers in C and the denominator is an integer, the compiler intends it as integer division. Therefore, if you split 1 divided by 2, it returns zero, not 0.5

In addition, your output variable is also an integer, therefore, if you expect decimal outputs, you will not get it.

You can fix this by doing:

float timeLapseInterval = totalLengthSecs / (float) totalFrames;

printf ("\ n \ n% f", timeLapseInterval);

I hope this helps

0
source

Source: https://habr.com/ru/post/1390437/


All Articles