开发者

PHP: calculating the average 3

Im working on a star rating (5 stars is best, 1 is bad), and i have 4 records of 4 users voted.

user1: 3
user2: 4
user3: 5
user4: 3

How can i calculate out the average of this in php?

Is it just simp开发者_JS百科le math, $count = $user1 + $user2 + $user3 + $user4/4 ?

I tried:

echo round(3+4+5+3/4);

and got the number "13" which is not right


In math division precedes addition, so you should rewrite your equation as (3 + 4 + 5 + 3) / 4


You're running into operator precedence. The division will be calculated before the addition, so you're getting this (with added brackets for clarity):

3 + 4 + 5 + (3 / 4)

... which is then rounded to 13.

Try this instead:

$count = ($user1 + $user2 + $user3 + $user4 ) / 4 


Divisions have precedence over additions. Instead of what you do, use

echo round((3+4+5+3)/4); 


You have 2 options how to store the votes.
a) separately as you do now (user1: 5; user2: 3; user3: 4;...)
b) or you can aggregate the votes

You most probably implemented option a), but let me show you what option b) is about.
When you aggregate votes, for each post/article/news you store only 2 values - number of votes and average rating.
This helps you to retrieve the average rating faster and easier every time you render a page.
However when a user casts his/her vote, you need to do a little math to update the average rating.

Suppose the stored values are as follows
average rating = 3.3
number of votes = 5

If user votes 3, you need to update both average rating and number of votes like this:
new number of votes = [old number of votes] + 1 (5 + 1 = 6)
new average rating =
([old average rating] * [old number of votes] + [current vote]) / [new number of votes] ((3.3 * 5 + 3) / 6 = 3.25)

However there is also a drawback to storing the votes this way - you don't get to see how individual users voted. If the requirement states you need to see how individual users voted, combine approach a) and b) and you're good to go.


You have to group your additions before the division.

echo round((3+4+5+3)/4);


<?php

echo round((3+4+5+3)/4); 


or
$user1=3;
$user2=4;
$user3=5;
$user4=3

echo $count = ($user1 + $user2 + $user3 + $user4 ) / 4 

op-->4
?>

Try this it 's work perfectly ..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜