根据我从问题中可以理解的情况,固定点可能会对您有所帮助。
定点允许您对整数进行十进制运算,假设小数点后的位数是预先知道的。
这是固定点的快速而肮脏的实现:
#include <stdio.h>
#define FP_ABS(x) ((x) >= 0 ? (x) : -(x))
// This will determine the number of digits after the decimal point.
// It must be a power of 10.
// In this case, you can represent all the numbers in the range -2147483.648 to 2147483.647
// or if you want to be safe -2000000.000 to 2000000.000
#define FP_DECIMAL_FACTOR 1000
#define FP_LIT(x) ((int)((x) * FP_DECIMAL_FACTOR))
#define FP_ADD(x, y) ((x) + (y))
#define FP_SUB(x, y) ((x) - (y))
#define FP_MUL(x, y) ((x) * (y) / FP_DECIMAL_FACTOR)
#define FP_DIV(x, y) ((x) * FP_DECIMAL_FACTOR / (y))
#define FP_INT_PART(x) ((x) / FP_DECIMAL_FACTOR)
#define FP_DEC_PART(x) (FP_ABS((x) % FP_DECIMAL_FACTOR))
int main()
{
int a = FP_LIT(25.01);
int b = FP_LIT(12.2);
printf("a = %d.%03d\n", FP_INT_PART(a), FP_DEC_PART(a));
printf("b = %d.%03d\n", FP_INT_PART(b), FP_DEC_PART(b));
int a_plus_b = FP_ADD(a, b);
printf("a + b = %d.%03d\n", FP_INT_PART(a_plus_b), FP_DEC_PART(a_plus_b));
int a_minus_b = FP_SUB(a, b);
printf("a - b = %d.%03d\n", FP_INT_PART(a_minus_b), FP_DEC_PART(a_minus_b));
int b_minus_a = FP_SUB(b, a);
printf("b - a = %d.%03d\n", FP_INT_PART(b_minus_a), FP_DEC_PART(b_minus_a));
int a_multiply_b = FP_MUL(a, b);
printf("a * b = %d.%03d\n", FP_INT_PART(a_multiply_b), FP_DEC_PART(a_multiply_b));
int a_divide_b = FP_DIV(a, b);
printf("a / b = %d.%03d\n", FP_INT_PART(a_divide_b), FP_DEC_PART(a_divide_b));
int b_divide_a = FP_DIV(b, a);
printf("b / a = %d.%03d\n", FP_INT_PART(b_divide_a), FP_DEC_PART(b_divide_a));
return 0;
}