Skip to content

Instantly share code, notes, and snippets.

@boki1
Last active May 30, 2019 21:32
Show Gist options
  • Save boki1/9900ef82be7ccd329cff3c456e73c3b2 to your computer and use it in GitHub Desktop.
Save boki1/9900ef82be7ccd329cff3c456e73c3b2 to your computer and use it in GitHub Desktop.
Float with fixed amount of digits after colon
#ifndef FFIXED_H
#define FFIXED_H
#endif // FFIXED_H
namespace number {
struct ffixed {
friend ffixed operator-(const ffixed &This, const ffixed &other);
friend ffixed operator+(const ffixed &This, const ffixed &other);
friend ffixed operator*(const ffixed &This, const ffixed &other);
friend ffixed operator/(const ffixed &This, const ffixed &other);
ffixed &operator=(const ffixed &r);
ffixed &operator=(double d);
ffixed() {}
ffixed(double d);
operator double() const;
private:
int nominator;
enum {
denominator = 1 << 10
};
};
}
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include "ffixed.h"
namespace number {
ffixed &ffixed::operator=(double d) {
this->nominator = d / this->denominator;
return *this;
}
ffixed &ffixed::operator=(const ffixed &r) {
this->nominator = r.nominator;
return *this;
}
ffixed::ffixed(double d) {
this->nominator = d * this->denominator;
}
ffixed::operator double() const {
return (double) this->nominator / this->denominator;
}
ffixed operator+(const ffixed &This, const ffixed &other) {
ffixed res;
res.nominator = This.nominator + other.nominator;
return res;
}
ffixed operator-(const ffixed &This, const ffixed &other) {
ffixed res;
res.nominator = This.nominator - other.nominator;
return res;
}
ffixed operator*(const ffixed &This, const ffixed &other) {
ffixed res;
res.nominator = (int) This.nominator * other.nominator / ffixed::denominator;
return res;
}
ffixed operator/(const ffixed &This, const ffixed &other) {
ffixed res;
res.nominator = This.nominator * ffixed::denominator / other.nominator;
return res;
}
}
namespace c {
extern "C" void init() {
number::ffixed a = 0.14, b = 0.33;
::printf("ADD: %f\n", (double) (a + b));
::printf("SUB: %f\n", (double) (a - b));
::printf("MUL: %f\n", (double) (a * b));
::printf("DIV: %f\n", (double) (a / b));
}
}
int main() {
c::init();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment