Last active
March 22, 2017 18:42
-
-
Save blippy/139fb0f2dff8703b6eae8129509d0d14 to your computer and use it in GitHub Desktop.
Decimal arithmetic C and C++ interoperability
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #ifdef __cplusplus | |
| #include <decimal/decimal> | |
| typedef std::decimal::decimal64::__decfloat64 Num; | |
| #else | |
| typedef _Decimal64 Num; | |
| #endif | |
| #ifdef __cplusplus | |
| extern "C" { | |
| #endif | |
| Num get_num(); | |
| void print_num(Num n); | |
| #ifdef __cplusplus | |
| } | |
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include "dec.h" | |
| Num get_num() | |
| { | |
| return 0.2DD; | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <decimal/decimal> | |
| #include <iostream> | |
| #include <iomanip> // for std::setprecision() | |
| #include "dec.h" | |
| void print_num(Num n) | |
| { | |
| std::decimal::decimal64 d64(n); | |
| std::cout << std::setprecision(20) << std::decimal::decimal_to_float(d64) << std::endl; | |
| // Output is 0.20000000298023223877 | |
| } | |
| int main() | |
| { | |
| Num n = get_num(); | |
| print_num(n); | |
| std::cout << ( 0.1 + 0.2 == 0.3) << std::endl; // false (0) | |
| std::cout << ( 0.1DD + 0.2DD == 0.3DD) << std::endl; // true (1) | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| dec : decc.o deccc.o | |
| g++ decc.o deccc.o -o dec | |
| decc.o : decc.c | |
| gcc -c decc.c | |
| deccc.o : deccc.cc | |
| g++ -c deccc.cc | |
| .PHONY : clean | |
| clean : | |
| rm -f *.o dec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment