是否应该避免这种从 int 到双精度的静态转换?

Should this static cast from int to double be avoided?

本文关键字:双精度 静态 转换 int 是否      更新时间:2023-10-16

考虑:

int total = 14; // something for which double does not make sense
int nPeople = 5;
double perCapita = static_cast<double>(total) / nPeople; // should this cast be avoided?

在这种情况下应该避免铸造吗?写1.0 * total / nPeople好还是别的好?

在这种情况下应该避免投射吗?写1.0更好吗 * 总计/n人还是别的什么?

乘以 1.0 并不能明确意图。此处的显式强制转换要清晰得多,并且是执行此操作的实际接受方式。如果我们有某种可以显式调用的模板函数(一个不叫std::div- 因为这是一种不同的划分(,那就太好了——但唉,我们没有,直到那时 - 只是static_cast<double>