C/working of +,/, - in c
Expert: Zlatko - 3/10/2010
QuestionDear sir,
I have a siple question I have
a=3+4/3*7
when I run a program I got answer 10
Please calrify that whay it is coming 10
as I understand 3+4=7 then 7/21 the ansewer shold 0.33
AnswerHello Rakesh
You are doing integer arithmetic in your program. With integer arithmetic, the fractional part is discarded. So we have:
4/3 = 1
1* 7 = 7
7 + 3 = 10
To get the answer you expect, convert at least one of the operands into floating point, and store the result in a float, like this:
float a = 3+4.0/3*7
Adding the the decimal point to one of the operands puts the multiplication and division term into floating point mode.
Note that it doesn't make the entire expression floating point, so if you have
float a = 4.0/3 + 4/3;
only the first division is floating point. The second is integer mode again.
Another way to convert a number to floating point is with a cast, like this:
int a
int b
float c = (float)a/b