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;;
多一个分号(空语句),不影响结果