为什么这个整数除法产生出0? [英] Why does this integer division yield 0?

查看:145
本文介绍了为什么这个整数除法产生出0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我,为什么下面的code在标线输出 0

看来仿佛一切都是正确的,但后来当我试图让附近它给我0每次最终结果。

 的#include<&stdio.h中GT;诠释主(){    //收集时间推移变量    INT帧率,totalLengthSecs;
    的printf(有多少帧每秒:);
    scanf函数(%i的,&安培;帧率);
    的printf( - >%I帧的证实。帧率);
    的printf(延时[秒]的\\ nDesired长:);
    scanf函数(%i的,&安培; totalLengthSecs);
    的printf( - 方式>%I秒证实,totalLengthSecs);
    INT totalFrames =帧率* totalLengthSecs;
    的printf(\\ n您需要%I帧。totalFrames);    //定时间隔计算    INT timeLapseInterval = totalLengthSecs / totalFrames;    的printf(\\ n \\ n%I,timeLapseInterval); //< - 这将打印0    返回0;
}


解决方案

在短期:整数除法截断

您需要以下内容:

 双timeLapseInterval =(双)totalLengthSecs /(双)totalFrames;
的printf(\\ ntimeLapseInterval:%F \\ N,timeLapseInterval);

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

解决方案

In short: Integer division truncates

You need the following:

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

这篇关于为什么这个整数除法产生出0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆