#include <iostream>
using namespace std;
template<int E>
struct BasicFixedReal
{
typedef BasicFixedReal self;
static const int factor = 1 << (E - 1);
BasicFixedReal() : m(0) {}
BasicFixedReal(double d) : m(static_cast<int>(d * factor)) {}
self& operator+=(const self& x) { m += x.m; return *this; }
self& operator-=(const self& x) { m -= x.m; return *this; }
self& operator*=(const self& x) { m *= x.m; m >> E; return *this; }
self& operator/=(const self& x) { m /= x.m; m *= factor; return *this; }
self& operator*=(int x) { m *= x; return *this; }
self& operator/=(int x) { m /= x; return *this; }
self& operator-() { return self(-m); }
double toDouble() const { return double(m) / factor; }
friend self operator+(self x, const self& y) { return x += y; }
friend self operator-(self x, const self& y) { return x -= y; }
friend self operator*(self x, const self& y) { return x *= y; }
friend self operator/(self x, const self& y) { return x /= y; }
friend bool operator==(const self& x, const self& y) { return x.m == y.m; }
friend bool operator!=(const self& x, const self& y) { return x.m != y.m; }
friend bool operator<(const self& x, const self& y) { return x.m < y.m; }
friend bool operator>(const self& x, const self& y) { return x.m > y.m; }
friend bool operator>=(const self& x, const self& y) { return x.m >= y.m; }
friend bool operator<=(const self& x, const self& y) { return x.m <= y.m; }
private:
int m;
};
typedef BasicFixedReal<10> FixedReal;
int main(int argc, char** argv)
{
FixedReal x(0);
for (int i = 0; i < 100; ++i) { x += FixedReal(0.0625);
}
cout << x.toDouble() << endl;
system("pause");
return 0;
}
实现固定小数位数值
最新推荐文章于 2023-04-19 00:16:46 发布
本文介绍了一个使用C++模板元编程实现的固定精度算术类库,该类库能够提供比浮点数更精确的数值计算,并且通过模板参数指定精度。文中提供了完整的类定义和一个简单的示例程序,演示了如何使用这个类来累积一系列相同的小数值。
1622

被折叠的 条评论
为什么被折叠?



