咖啡店的評分,每人給 1 到 5 顆星。寫一行:用 accumulate 把 stars 加起來放進 total。平均數是整數相除,去掉小數;沒人評分就返回 0(模板裡寫好了)。
average_stars({5, 4, 4})→4average_stars({})→0int average_stars(const vector<int> &stars)#include <numeric>
#include <vector>
using namespace std;
int average_stars(const vector<int> &stars) {
if (stars.empty()) {
return 0;
}
int total = 0;
// 在這裡寫:用 accumulate 算 total
return total / stars.size();
}
寫好了先點「執行」試試示例,沒問題再點「提交」。