View Full Version : Help in C Arithmetics
uaecasher
Jun 16, 2009, 01:24 AM
Hello,
i have written this code:
#include <stdio.h>
int main (void)
{
int a = 15;
int b = 35;
printf("a / b * b = %i\n", a / b * b);
}
the result i get is zero, but it should be 15, why I'm getting a 0
thanks
Wes
Jun 16, 2009, 01:38 AM
You need to think about the order this is being evaluated, see: http://www.difranco.net/cop2220/op-prec.htm
a / b * b becomes (a / b) * b
where:
a = 15;
b = 35;
(15/35)*35
0*35
Remember these are integers so 15/35 will be 0. If you want to get the fractional part you'll need to use floats or doubles.
EMT
Jun 16, 2009, 01:57 AM
Use parenthesis in your expressions to make it safe.:
Sander
Jun 16, 2009, 02:11 AM
Use parenthesis in your expressions to make it safe.:
That wouldn't help in this case - it's the integer division that's the problem here.
gnasher729
Jun 16, 2009, 05:51 AM
Hello,
i have written this code:
#include <stdio.h>
int main (void)
{
int a = 15;
int b = 35;
printf("a / b * b = %i\n", a / b * b);
}
the result i get is zero, but it should be 15, why I'm getting a 0
thanks
It should be zero. Buy a C book for beginners.
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.