C语言常见错误分析
时间:2010-11-20 来源:osullishuai80
(一)浮点数的比较
【规则】不可将浮点变量用"=="或"!="与任何数进行比较
【例程】根据学生分数来显示学生信息
#include <stdio.h>
#define EPSINON 1e-6 //允许的误差
typedef struct student
{
int id;
char name[20];
float score;
}Student;
int search(Student *p ,int n ,float key); int main(int argc,char *argv[])
{
Student stu[4] = {
{100,"beibei",98.5},
{101,"jingjing",96.5},
{102,"huanhuan",94.5},
{103,"yingying",95}
};
float val;
int ret;
printf("Please input your expected score:\n");
scanf("%f",&val);
ret = search(stu,4,val);
printf("学号\t姓名\t分数\n");
printf("%d %s %f\n",stu[ret].id,stu[ret].name,stu[ret].score);
return 0;
} int search(Student stu[] ,int n ,float key)
{
int i;
float value;
for(i=0;i<n;i++)
{
value= stu[i].score-key;
if((value<EPSINON)&&(value>-EPSINON))
return i;
}
return -1;
} 【执行结果】 Please input your expected score: 95 103 yingying 95.000000 【attention】 无论是float还是double类型的变量,都有精度限制,所以一定要避免将浮点型变量与数字进行直接比较,应该设法转化成">="或"<="的形式.假设浮点型变量名为x,则应该将 if(x == 0.) //隐含错误比较 转化为 if((x>=-EPSINON)&&(x<=EPSINON)) 其中,EPSINON是允许的误差,即精度.
{
int id;
char name[20];
float score;
}Student;
int search(Student *p ,int n ,float key); int main(int argc,char *argv[])
{
Student stu[4] = {
{100,"beibei",98.5},
{101,"jingjing",96.5},
{102,"huanhuan",94.5},
{103,"yingying",95}
};
float val;
int ret;
printf("Please input your expected score:\n");
scanf("%f",&val);
ret = search(stu,4,val);
printf("学号\t姓名\t分数\n");
printf("%d %s %f\n",stu[ret].id,stu[ret].name,stu[ret].score);
return 0;
} int search(Student stu[] ,int n ,float key)
{
int i;
float value;
for(i=0;i<n;i++)
{
value= stu[i].score-key;
if((value<EPSINON)&&(value>-EPSINON))
return i;
}
return -1;
} 【执行结果】 Please input your expected score: 95 103 yingying 95.000000 【attention】 无论是float还是double类型的变量,都有精度限制,所以一定要避免将浮点型变量与数字进行直接比较,应该设法转化成">="或"<="的形式.假设浮点型变量名为x,则应该将 if(x == 0.) //隐含错误比较 转化为 if((x>=-EPSINON)&&(x<=EPSINON)) 其中,EPSINON是允许的误差,即精度.
相关阅读 更多 +