Wednesday, February 15, 2012

Why doesn't the c program calculate the percentage correctly even if i use a pair of parentheses into it?

Here is the expression, per=5000*40/100

Can someone please explain how C evaluates an expression having same precedence.Why doesn't the c program calculate the percentage correctly even if i use a pair of parentheses into it?
What? Which answer do you expect? 5000*40/100 gives 2000 in both C and on my calculator and in my head.



Is per defined as a float or a double? Have you tried 5000*40/(float)100 ?Why doesn't the c program calculate the percentage correctly even if i use a pair of parentheses into it?
if the numbers are integers, C will do integer division and multiplication.

according to math rules, multiplication and division have precedence over addition and subtraction.

if they are all multiplies and divides, they are evaluated left to right.



5000*40 will be the first evaluation, which evaluates to 200000



200000/100 will be the next evaluation, which is 2000



if you had more interesting numbers which don't divide evenly, like this:

0/3=0 0%3=0

1/3=0 1%3=1

2/3=0 2%3=2

3/3=1 3%3=0

4/3=1 4%3=1

5/3=1 5%3=2

6/3=2 6%3=0

7/3=2 7%3=1

8/3=2 8%3=2



that's integer division.

if you want to force floating point division, simply append .0 to one of the numbers. for instance,

double num=8.0/3; //2.666666667;



I have no context/meaning for the numbers, so I cannot help you with the percentage calculation.Why doesn't the c program calculate the percentage correctly even if i use a pair of parentheses into it?
Hi,



The expression per=5000*40/100 evaluates to per = 2000.



Did you mean per=5000*100/40 which evaluates to per = 12500?



Hope this helps.
  • car battery
  • nada guides
  • No comments:

    Post a Comment