简体   繁体   English

为什么这个整数除法产生0?

[英]Why does this integer division yield 0?

Could someone tell me why the following code is outputting 0 at the marked line? 有人能告诉我为什么下面的代码在标记的行输出0

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. 似乎一切都是正确的,但是当我试图将结果接近结束时,它每次给我0。

#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;
}

In short: Integer division truncates 简而言之:整数除法截断

You need the following: 您需要以下内容:

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

You are performing integer math. 您正在执行整数数学。

Math between two integers will produce an integer. 两个整数之间的数学将产生一个整数。 And the result will be rounded towards zero. 结果将四舍五入为零。

This line: 这一行:

totalLengthSecs / totalFrames;

Is likely producing a result that's between 0 and 1 . 可能产生的结果介于01之间。 And getting rounded to 0 并四舍五入到0

You are printing integers and therefore it will round down the value. 您正在打印整数,因此它将向下舍入该值。

timeLapseInterval / totalFrames will be (1 / frameRate) which will be < 1 unless frameRate is 1 (or 0 in which case you have an error dividing by 0) timeLapseInterval / totalFrames将是(1 / frameRate) ,除非frameRate为1(或0,在这种情况下你有一个错误除以0),它将<1

When you divide 2 numbers in C and the denominator is integer, the compiler intends it as an integer division. 当您在C中分割2个数字并且分母是整数时,编译器将其视为整数除法。 Therefore, if you divide 1 divided 2, it returns zero and not 0.5 因此,如果将1除以2,则返回零而不是0.5

Moreover, your output variable is an integer too, hence, if you expect decimal outputs, you won't get it. 此外,您的输出变量也是一个整数,因此,如果您期望十进制输出,您将无法得到它。

You can fix it by doing: 你可以通过这样做来解决它:

float timeLapseInterval = totalLengthSecs / (float)totalFrames; float timeLapseInterval = totalLengthSecs /(float)totalFrames;

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

I hope this helps 我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM