Math Is Fun Forum

  Discussion about math, puzzles, games and fun.   Useful symbols: ÷ × ½ √ ∞ ≠ ≤ ≥ ≈ ⇒ ± ∈ Δ θ ∴ ∑ ∫ • π ƒ -¹ ² ³ °

You are not logged in.

#1 2011-01-17 18:14:33

simy202
Member
Registered: 2011-01-17
Posts: 1

Basic PHP Math Question

I'm going through a php tutorial right now and this math example below is driving me nuts. The exmaple was "((1 + 2 + $var1) * $var2) / 2 - 5", and all the rest of the code below is just me trying to figure it out.

The answer ends up being "7", but to me it looks like PHP is sayding "24 / -3 = 7" when it should be "24 / -3 = -8". What am I missing in this PHP Math issue?? Thanks!

<?php
$var1 = 3;
$var2 = 4;
?>
    $var1 = 3;<br />
        $var2 = 4;<br /><br />
       <br />
       <h1> ((1  + 2 + $var1) * $var2) / 2 - 5 = <?php echo((1  + 2 + $var1) * $var2) / 2 - 5; ?><br /> </h1>
    <hr />
    <br />
    <br />
    LEFT SIDE:<br />
    (1  + 2 + $var1) * $var2 =  <?php echo ((1  + 2 + $var1) * $var2); ?><br />
<br />
RIGHT SIDE:<br />
2 - 5 =   <?php echo 2 - 5; ?><br />
    <br />
    24 / -3 SHOULD BE:
    <h1>24 / -3 = <?php echo 24 / -3; ?><br /></h1>

That spits out:

    $var1 = 3;
    $var2 = 4;

    ((1 + 2 + $var1) * $var2) / 2 - 5 = 7

    LEFT SIDE:
    (1 + 2 + $var1) * $var2 = 24

    RIGHT SIDE:
    2 - 5 = -3

    24 / -3 SHOULD BE:
    24 / -3 = -8

Offline

#2 2011-01-17 18:51:34

gAr
Member
Registered: 2011-01-09
Posts: 3,482

Re: Basic PHP Math Question

Hi simy202,

I guess you haven't read about operator precedence.
Please refer this: http://www.php.net/manual/en/language.operators.precedence.php

echo((1  + 2 + $var1) * $var2) / 2 - 5;

This evaluates to : (((1 + 2 + 3)*4)/2) - 5 = ((6*4)/2) - 5 = 12 - 5 = 7.
If you want it to be -8, rewrite it as:

echo((1  + 2 + $var1) * $var2) / (2 - 5);

The left of '=' sign is called Left hand side, not the left of '/' sign...

Last edited by gAr (2011-01-17 18:55:20)


"Believe nothing, no matter where you read it, or who said it, no matter if I have said it, unless it agrees with your own reason and your own common sense"  - Buddha?

"Data! Data! Data!" he cried impatiently. "I can't make bricks without clay."

Offline

#3 2011-02-08 14:38:21

gAr
Member
Registered: 2011-01-09
Posts: 3,482

Re: Basic PHP Math Question

Hi Shivamcoder3013,

PHP code doesn't work outside <?php   ?> tags. It will simply print it as it is.


"Believe nothing, no matter where you read it, or who said it, no matter if I have said it, unless it agrees with your own reason and your own common sense"  - Buddha?

"Data! Data! Data!" he cried impatiently. "I can't make bricks without clay."

Offline

Board footer

Powered by FluxBB