0%

【C++】每日 Bug - int 转 double

算是一个挺常见的错误(对于我来说),印象中是第二次犯这个错了。

看下面这个函数,你觉得有没有什么问题?

1
2
3
4
5
6
7
double count_avg(vector<int>nums) {
int ans = 0;
for (auto num : nums) {
ans += num;
}
return ans / nums.size();
}

看上去没毛病,这个函数就是求平均值嘛,先求和然后除以个数,得到的结果不就是平均值嘛,来几个测试用例看看:

1
2
3
4
5
6
cout << count_avg({2, 2}) << endl;
// 2
cout << count_avg({1, 3}) << endl;
// 2
cout << count_avg({2, 3}) << endl;
// 2!

最后一个例子出现问题了,聪明的你发现了问题所在吗?

因为 ans 是 int 类型,而 size() 返回是一个 vector::size_type 类型,就把它当作 int 类型(一般都用 int size 去接嘛),所以最后结果就是个 int 的类型,对于除不断的就直接取整了,所以需要操作一波,把 ans 或者 size 转换成 double 类型。

Welcome to my other publishing channels