Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this integer division yield 0?

Tags:

c

variables

math

Could someone tell me why the following code is outputting 0 at the marked line?

It seems as if everything is correct but then when I try to get the result near the end it's giving me 0 each 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;
}
like image 607
Chris Avatar asked Feb 22 '23 21:02

Chris


1 Answers

In short: Integer division truncates

You need the following:

double timeLapseInterval = (double) totalLengthSecs / (double)totalFrames;
printf("\ntimeLapseInterval : %f \n", timeLapseInterval);
like image 135
Sangeeth Saravanaraj Avatar answered Mar 03 '23 16:03

Sangeeth Saravanaraj