Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division result is always zero [duplicate]

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

like image 693
VaioIsBorn Avatar asked Feb 27 '10 01:02

VaioIsBorn


People also ask

Can a division result in zero?

These notes discuss why we cannot divide by 0. The short answer is that 0 has no multiplicative inverse, and any attempt to define a real number as the multiplicative inverse of 0 would result in the contradiction 0 = 1.

How does division work in C?

In the C Programming Language, the div function divides numerator by denominator. Based on that division calculation, the div function returns a structure containing two members - quotient and remainder.

What happens when you attempt a division by zero in C?

Regarding division by zero, the standards say: C99 6.5. 5p5 - The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.


1 Answers

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;
like image 188
John Knoeller Avatar answered Sep 30 '22 18:09

John Knoeller