#include <stdio.h>
#include <math.h> /* fabs */
#ifdef _WIN32
// #include <Windows.h>
#endif
//输出的数值不断递增,即使将10改成10.0,循环也没有中止,为什么?
void test_float001()
{
double i;
for(i=0; i != 10; i += 0.1)
{
printf("%.1f\n", i);
#ifdef _WIN32
Sleep(100);
#endif
}
}
//https://www.zhihu.com/question/32304267
//按不同精度输出
void test_float002()
{
double i;
int j;
for(i = 0, j = 0; j != 101; j++, i += 0.1)
{
printf("%.20lf\t %.1f\n", i, i);
#ifdef _WIN32
Sleep(100);
#endif
}
//因为十进制浮点数无法转化为精确的二进制浮点数,所以,你得到的结果注定是不精确的,所以累加以后也永远得不到精确的10.0
}
//1、float double浮点型相等判断。
/* a == b*/
int dequals(double a, double b)
{
double c=fabs(a-b);//一定要#include <math.h> labs 针对long整数 fabs针对浮点数,abs针对整数
return c< 0.000001;
}
void test_abs()
{
int c=-3;
float b=-4.3;
printf("c的绝对值:%d\n",abs(c));
printf("b的绝对值:%ld\n",fabs(b));
printf("b的绝对值:%f\n",fabs(b));
printf ("The absolute value of 3.1416 is %f\n", fabs(3.1416));
printf ("The absolute value of -10.6 is %f\n", fabs(-10.6));
}
//C语言中浮点数double/float相等判断
int main(void)
{
test_abs();
double a=0.89999999999999991000;
double b=0.9;
if(a==b)
{
printf("a==b\n");
}else{
printf("a!=b\n");
}
b=0.89999999999999992200;//后面的精度就是接近值了
if(a!=b)//这里居然是相等的
{
printf("a!=b\n");
}else{
printf("a==b\n");
}
if(dequals(a,b))
{
printf("a==b\n");
}else{
printf("a!=b\n");
}
if (abs(a - b)<0.0001)
{
printf("a==b\n");
}else{
printf("a!=b\n");
}
// test_float001();
test_float002();
return 0;
}
C语言中浮点数double/float相等判断
最新推荐文章于 2024-08-13 10:42:49 发布