整数和浮点数作比较差异点(持续更新)
问题1、整数可以在C语言中直接比较,为射门浮点不可以直接比较。
解:整数可以直接进行比较,而浮点数由于存在精度问题,不能直接进行比较。
2、那该怎么比较?举个例子
解:浮点数的比较需要使用fabs函数取绝对值来解决精度问题。
#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable:6031)
#include <stdio.h>
#include <string.h>
#include <math.h>
int main()
{
int a = 4, b = 5;
float c = 3.14, d = 2.71;
if (a < b) {
printf("a is less than b\n");
}
else {
printf("a is greater than or equal to b\n");
}
if (c < d) {
printf("c is less than d\n");
}
else {
printf("c is greater than or equal to d\n");
}
if (fabs(c - d) < 0.001)//这一条不能少,否则精度则出现问题
{
printf("c is equal to d\n");
}
else if (c < d) {
printf("c is less than d\n");
}
else {
printf("c is greater than d\n");
}
return 0;
}
3、如果不加if里的判断,会造成什么结果?
解:如果不加if(fabs(c-d)<0.001),可能会影响判断c和d的大小,因为浮点数存在精度问题,在没有进行精度控制的情况下,相等的两个浮点数可能会被判断为不相等。因此,对于浮点数的大小比较,一般需要使用精度控制,如示例中使用的if(fabs(c-d)<0.0001)来判断c和d是否相等