我正在构建一个具有极坐标系和笛卡尔坐标系以及三维坐标系的世界。我的坐标都表示为浮点数。我开始写测试,然后从那里开始编码。一切都很好,直到我开始尝试精确的数值,然后我开始出现问题。
下面是一个示例测试:
TEST_METHOD(TestAngleFromPointUsingRelativeCoordsQuandrant1_1)
{
TwoDCoordinate testPoint = TwoDCoordinate(10, 10);
PolarCoordinate expected = PolarCoordinate(45.0F, 14.142136F);
PolarCoordinate actual = CoordinateConverter::ConvertFrom2DToPolar(testPoint);
TwoDCoordinate convertedCoord = CoordinateConverter::ConvertFromPolarTo2D(actual, TwoDCoordinate(0.0F, 0.0F));
ActAndAssertOnConversion(expected, actual);
}
14.142136的值对我来说太精确了,14.142就可以了。所以我去研究了更多的std方法,发现了std::stof。基于此,我编写了此函数:
float BaseTester::RoundFloatTo(float fnum, int round_digits)
{
std::string::size_type sz;
std::ostringstream oss;
oss << std::fixed << std::showpoint;
oss << std::setprecision(round_digits);
oss << fnum;
std::string buffer = oss.str();
return std::stof(buffer, &sz);
}
我以为我的麻烦已经过去了,直到我看到精度从5到0的输出。对于浮动14.142136,我得到:
-
5 = 14.1421404
-
4 = 14.1421003
-
3 = 14.1420002
-
2 = 14.1400003
-
1 = 14.1000004
-
0 = 14.0000000
这根本不是我所期望的!我希望数字的数量会随着精度的降低而减少,并适当地向上或向下取整。这样地:
-
5 = 14.14214
-
4 = 14.1421
-
3 = 14.142
-
2 = 14.14
-
1 = 14.1
-
0 = 14.0
很明显我做错了什么,有人有什么好主意吗?