Division result is always zero [duplicate]
Asked Answered
B

4

23

I got this C code.

#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) ?

Bedding answered 27/2, 2010 at 1:37 Comment(2)
See also #1580832Ephemerality
lol - integer division in c was my very first head scratcher too. No stack over flow then - just a humorless profMonthly
F
31

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

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;
Farcy answered 27/2, 2010 at 1:38 Comment(3)
Or just use d / 100.0.Sundae
In my situation this is what I ended up doing to stop getting 0 for my division: Double ratio = (Convert.ToDouble(x) / Convert.ToDouble(y));Pythagoreanism
@ChristopherD.Emerson That is C#; this question is about C (and also applies to C++).Collette
C
0

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

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:

t = (int)((1.0 / 100.0) * d);
Chaffee answered 27/2, 2010 at 1:38 Comment(0)
M
0

I think its because of

t = (1/100) * d;

1/100 as integer division = 0

then 0 * d always equals 0

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

Massa answered 27/2, 2010 at 1:40 Comment(0)
J
-3
t = (1/100) * d; 

That is always equals 0,you can do this

t=(1%100)*d 

and add it to 0

Jecoa answered 13/11, 2016 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.