为什么我会从' double'转换到“浮动”,可能丢失数据警告?(c)

时间:2014-12-13 17:03:56

标签: c visual-studio

我正在编写一个程序,它基本上计算了进口汽车的关税。用户应该输入汽车价格和货物价值。但是当我计算时,我得到的这个错误并不好。

//导致汽车充电的总费用//

main()
{

        float purchaseprice, shipmentcosts, ecowaslevy, importlevy, GCNETlevy, TotalDuty;

        printf("Enter the purchase price and shipment cost");


        scanf("%f,%f", &purchaseprice, &shipmentcosts);
        ecowaslevy = 0.01f, importlevy = 0.25f, GCNETlevy = 0.05f;
        //FORMULAS FOR THE LEVY//
        ecowaslevy = (purchaseprice + shipmentcosts) * (0.01); 
        importlevy = (purchaseprice + shipmentcosts) * (0.25); 
        GCNETlevy =  (purchaseprice + shipmentcosts) * (0.05); 
        //FORMULA FOR TOTAL DUTY//
        TotalDuty = (ecowaslevy + importlevy + GCNETlevy)*(3.2);
        printf("TOTAL DUTY=GHC.%f", TotalDuty);
        system("pause");

}

这些是警告:

  

1> c:\ users \ david \ documents \ visual studio 2013 \ projects \ total expenses \ total expenses \ tot.c(9):警告C4244:' =' :转换为' double' “浮动”,可能导致数据丢失

1> c:\ users \ david \ documents \ visual studio 2013 \ projects \ total expenses \ total expenses \ tot.c(10):警告C4244:' =' :转换为' double' “浮动”,可能导致数据丢失

1> c:\ users \ david \ documents \ visual studio 2013 \ projects \ total expenses \ total expenses \ tot.c(11):警告C4244:' =' :转换为' double' “浮动”,可能导致数据丢失

2 个答案:

答案 0 :(得分:3)

在多行中,您乘以0.010.25等常量值。这些值是双精度数,乘法结果是double,然后存储在精度较低的浮点变量中。这会给你一个编译器警告。要修复它,您可以将f文字后缀附加到常量值,例如0.01f0.25f等。

答案 1 :(得分:0)

因为sizeof(double) > sizeof(float)因此你的精确度会下降。