浮点值的二进制表示形式影响浮点计算的精度和准确性。Microsoft Visual C++ 使用 IEEE 浮点格式。
示例
复制代码
// Floating-point_number_precision.c
// Compile options needed: none. Value of c is printed with a decimal
// point precision of 10 and 6 (printf rounded value by default) to
// show the difference
#include <stdio.h>
#define EPSILON 0.0001 // Define your own tolerance
#define FLOAT_EQ(x,v) (((v - EPSILON) < x) && (x <( v + EPSILON)))
int main() {
float a, b, c;
a = 1.345f;
b = 1.123f;
c = a + b;
// if (FLOAT_EQ(c, 2.468)) // Remove comment for correct result
if (c == 2.468) // Comment this line for correct result
printf_s("They are equal.\n");
else
printf_s("They are not equal! The value of c is %13.10f "
"or %f",c,c);
}
输出
They are not equal! The value of c is 2.4679999352 or 2.468000
double floor(
double x
);
float floor(
float x
); // C++ only
long double floor(
long double x
); // C++ only
float floorf(
float x
);
Parameters
x
Floating-point value.
// crt_floor.c
// This example displays the largest integers
// less than or equal to the floating-point values 2.8
// and -2.8. It then shows the smallest integers greater
// than or equal to 2.8 and -2.8.
#include <math.h>
#include <stdio.h>
int main( void )
{
double y;
y = floor( 2.8 );
printf( "The floor of 2.8 is %f\n", y );
y = floor( -2.8 );
printf( "The floor of -2.8 is %f\n", y );
y = ceil( 2.8 );
printf( "The ceil of 2.8 is %f\n", y );
y = ceil( -2.8 );
printf( "The ceil of -2.8 is %f\n", y );
}
Output
The floor of 2.8 is 2.000000
The floor of -2.8 is -3.000000
The ceil of 2.8 is 3.000000
The ceil of -2.8 is -2.000000