C语言 除法结果始终为零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2345902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:38:15  来源:igfitidea点击:

Division result is always zero

cdoubledivisionmultiplicationinteger-division

提问by VaioIsBorn

I got this C code.

我得到了这个 C 代码。

#include <stdio.h>

int main(void)
{
        int n, d, i;
        double t=0, k;
        scanf("%d %d", &n, &d);
        t = (1/100) * d;
        k = n / 3;
        printf("%.2lf\t%.2lf\n", t, k);
        return 0;
}

I want to know why my variable 't' is always zero (in the printf function) ?

我想知道为什么我的变量 't' 始终为零(在 printf 函数中)?

回答by John Knoeller

because in this expression

因为在这个表达式中

t = (1/100) * d;

1 and 100 are integer values, integer division truncates, so this It's the same as this

1 和 100 是整数值,整数除法截断,所以 this 和 this 一样

t = (0) * d;

you need make that a float constant like this

你需要把它变成一个像这样的浮动常量

t = (1.0/100.0) * d;

you may also want to do the same with this

你可能也想用这个做同样的事情

k = n / 3.0;

回答by MikeP

You are using integer division, and 1/100 is always going to round down to zero in integer division.

您正在使用整数除法,并且 1/100 总是会在整数除法中向下舍入为零。

If you wanted to do floating point division and simply truncate the result, you can ensure that you are using floating pointer literals instead, and d will be implicitly converted for you:

如果您想进行浮点除法并简单地截断结果,您可以确保您使用的是浮点字面量,并且 d 将为您隐式转换:

t = (int)((1.0 / 100.0) * d);

回答by Eric

I think its because of

我认为是因为

t = (1/100) * d;

1/100 as integer division = 0

1/100 作为整数除法 = 0

then 0 * d always equals 0

那么 0 * d 总是等于 0

if you do 1.0/100.0 i think it will work correctly

如果你做 1.0/100.0 我认为它会正常工作

回答by Alex

t = (1/100) * d; 

That is always equals 0,you can do this

那总是等于0,你可以这样做

t=(1%100)*d 

and add it to 0

并将其添加到 0