首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

float型数据代数运算的疑问,该如何处理

2012-02-19 
float型数据代数运算的疑问有如下代码:#includestdio.h#definetax0.08main(){floatcost,total,shipping

float型数据代数运算的疑问
有如下代码:


#include   <stdio.h>
#define   tax   0.08;
main()
{
float   cost,total,shipping;

printf( "Enter   the   cost   of   the   item: ");
scanf( "%f ",&cost);

printf( "Enter   the   shipping   charge: ");
scanf( "%f ",&shipping);

total=cost+cost*tax+shipping;
printf( "The   total   is   %f: ",total);
}
当我输入100,200后的结果却是108.000000,而不是308.000000,然后我把它改成


#include   <stdio.h>
#define   tax   0.08;
main()
{
float   cost,total,a,shipping;

printf( "Enter   the   cost   of   the   item: ");
scanf( "%f ",&cost);

printf( "Enter   the   shipping   charge: ");
scanf( "%f ",&shipping);

a=cost+cost*tax;
                  total=a+shipping;

printf( "The   total   is   %f: ",total);
}却对了,为什么啊?


[解决办法]
#define tax 0.08;
因为你的0.08后面多了一个分号;
导致total=cost+cost*tax+shipping;变成2个表达式
total=cost+cost*0.08;
+shipping;
然后total就是108

而下面的
a=cost+cost*tax;
a=cost+cost*0.08;;
多一个分号(空语句),不影响结果

热点排行
Bad Request.