4

I am working on a Facebook App that needs to be able to average three numbers. But, it always return 0 as the answer. Here is my code:

$y = 100;
$n = 250;
$m = 300;
$number = ($y + $n + $m / 3);
echo 'Index: '.$number;

It always displays Index: 0

Any ideas?

Zac Brown
  • 5,905
  • 19
  • 59
  • 107
  • So, with your edited version it displays "Index: 450". With casablancas fix for operator precedence, "Index 216.666666667". Are you still having a problem with this? – JAL Nov 03 '10 at 04:09
  • Actually.. everything was right. All the numbers in the DB were set to 0! :) Corrected that, but how do I round the result? – Zac Brown Nov 03 '10 at 04:11

3 Answers3

11
$y = 100;
$n = 250;
$m = 300;
$number = ($y + $n + $m) / 3;
echo 'Index: '.$number;

Also - you missed ; in the end of the first 3 lines

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • 1
    @Zach, no it doesn't. So probably, `$y`, `$n`, and `$m` aren't getting initialized as you expect. – Matthew Flaschen Nov 03 '10 at 04:03
  • @Zachary Brown: copy-paste my code into the blank file and see the result. – zerkms Nov 03 '10 at 04:03
  • @zerkms, that wokred.. which means that it is an issue with the numbers from the DB. However, I also need it rounded to the nearest whole number. There a PHP way for that? – Zac Brown Nov 03 '10 at 04:08
  • @Zachary Brown: just wrap all the expression with `floor()` then – zerkms Nov 03 '10 at 04:11
  • @JustcallmeDrago: oops, i've read him as "the lowest whole number"... sure, `round()` then – zerkms Nov 03 '10 at 04:15
  • Im really sorry If my question is dumb, but still shouldnt it display a value? for example: (100 + 250 + 100) = 450. Or am I wrong? Because he missed the formation to get returned the average of the 3, but that doesnt mean maths stop there. – Periklis Kakarakidis Nov 19 '21 at 07:42
  • "shouldnt it display a value" --- display it where and by what? – zerkms Nov 19 '21 at 08:12
4

Your parentheses are grouped wrongly. You should be doing:

$number = ($y + $n + $m) / 3;
casablanca
  • 69,683
  • 7
  • 133
  • 150
  • @Zachary Brown: You're missing semicolons in the previous lines - it won't even parse with that, I wonder how you get a 0. – casablanca Nov 03 '10 at 04:04
1

Two problems:

You are missing ; at the end of these lines:

$y = 100
$n = 250
$m = 300

And to / has higher precedence than + so you need to do:

$number = ($y + $n + $m) / 3;
codaddict
  • 445,704
  • 82
  • 492
  • 529