ZeroJudge A866: Product Review Site

You need a program to assist a newly established online shopping website in reviewing product ratings. The ratings range from 1 to 5, and when users search for a product, the system must display the product's history, including the number of ratings for each level, a bar chart, and the average rating.

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
EOF inputs: each set of data represents the historical ratings of a product. Each line contains a rating (an integer from 1 to 5), and the data ends with a 0.The output consists of six lines, each representing the information for ratings 5 to 1. Each line includes the rating level, the number of ratings (padded with spaces if less than ten), and a bar chart (using "=" to represent the number of ratings). The last line outputs the average rating (rounded to four decimal places). See the example output for detailed formatting.
4
5
3
4
2
4
3
5
2
1
3
2
4
3
2
4
3
3
2
4
3
3
5
3
1
4
3
2
4
5
4
3
4
3
3
4
3
0
5 ( 4) |====
4 (11) |===========
3 (14) |==============
2 ( 6) |======
1 ( 2) |==
Average rating: 3.2432

Thought Process

Use a map to store the data. For the average value output, you can use printf to format the output to four decimal places.

Sample Code-ZeroJudge A866: Product Review Site

#include <iostream>
#include <stdio.h>
#include <map>
using namespace std;

int main() {
    int N, count = 0;
    double sum = 0;
    map<int, int>MAP;
    while (cin >> N && N != 0)
    {
        MAP[N]++;
        sum += double(N);
        count++;
    }
    map<int, string>result;
    int maxLen = -999;
    double avg = sum / double(count);
    for (int i = 5; i>0; i--)
    {
        result[i] = to_string(MAP[i]);
        int len = result[i].length();
        if (len > maxLen) maxLen = len;
    }
    for (int i = 5; i>0; i--)
    {
        cout << i << " (";
        for (int j = result[i].length(); j<maxLen; j++)
        {
            cout << " ";
        }
        cout << MAP[i] << ") |";
        for (int j = 0; j<MAP[i]; j++)
        {
            cout << "=";
        }
        cout << "\n";
    }
    printf("Average rating: %.4f\n", avg);
}

//ZeroJudge A866
//Dr. SeanXD

Comments