how to calculate average rating
Sorry if I am not clear:
How would I calculate the average rating based on the MinRate and MaxRate
for example: minRate = 0 or 1 and MaxRate = 2 or 3 or 4 or 5 or 0
How would I calculate the rating?
Update End
I am implementing a 5 star rating system and my table structure has two columns: 1) MinRate 2) MaxRate
so my question is: how do calculate the average rating?
here is how I have in my 5 star rating implementation.
int[] {7, 0, 0, 8, 5};
This means that:
- 7 users rated the articl开发者_StackOverflow中文版e with a 1
- 0 users rated the article with a 2
- 0 users rated the article with a 3
- 8 users rated the article with a 4
- 5 users rated the article with a 5
int[] x = {7, 0, 0, 8, 5};
/*
7 x 1 star
0 x 2 stars
0 x 3 stars
8 x 4 stars
5 x 5 stars
*/
float totalVoters = 0;
float totalPoints = 0;
for(i = 1; i <= x.length; i++)
{
//add 7, 0, 0, 8, 5
totalVoters += x[i];
/* add
7 x 1 star = 7,
0 x 2 stars = 0,
0 x 3 stars = 0,
8 x 4 stars = 32,
5 x 5 stars = 25
*/
totalPoints += x[i] * i;
}
response.write(totalPoints/totalVoters); //get the average
I don't really know ASP.NET, but the average is just the total divided by the number of items:
(int[0] + int[1] * 2 + int[2] * 3 + int[3] * 4 + int[4] * 5) / 5
So in a loop (won't work, as int
is reserved, but you get the idea):
float average = 0;
for (int i = minrate; i < maxrate; i++) {
average += int[i] * i;
}
average /= maxrate;
Here is some pseudo code:
double avg = 0;
for (int i = 0; i < arr.Length; i++) // arr.Length should be the same as MaxRate
{
avg += arr[i] * (i + MinRate);
}
avg /= arr.length;
((7*1)+(8*4)+(5*5))/(7+8+5) = 3.2
This is what i did
private static double GetRating()
{
int star5 = 12801;
int star4 = 4982;
int star3 = 1251;
int star2 = 429;
int star1 = 1265;
double rating = (double)(5 * star5 + 4 * star4 + 3 * star3 + 2 * star2 + 1 * star1) / (star1 + star2 + star3 + star4 + star5);
rating = Math.Round(rating, 1);
return rating;
}
static void Main(string[] args)
{
double rating = GetRating();
Console.WriteLine("Your product rating: " + rating);
Console.ReadKey();
}
Here's my solution to use in the 5 of 5 votes:
// 36 = excellent (5), 49 = good (4), 17 = average (3), 5 = bad (2), 9 = terrible (1)
var values = new[] {36, 49, 17, 5, 9};
var result = GetRating(values).ToString(CultureInfo.InvariantCulture);
MessageBox.Show(result); // 3.84
public static double GetRating(int[] ratings)
{
double ratingsSum = 0;
double ratingsTotal = 0;
for (var i = 1; i <= 5; i++)
{
ratingsSum += ratings[i - 1];
ratingsTotal += i * ratings[5 - i];
}
var average = ratingsTotal / ratingsSum;
return Math.Round(average, 2);
}
精彩评论