Dividing by 100 returns 0

后端 未结 6 1873
一向
一向 2021-01-17 02:13

I just wanted to calculate the VAT, but when i divide by 100 to obtain the total price (price*VAT/100), but it returns me 0.0. Here\'s my code:

        a.pri         


        
6条回答
  •  旧巷少年郎
    2021-01-17 03:02

    The problem is that what you're putting in your float variable is the result of operations on integers: it's an integer. In other words, a.precio * a.iva / 100 is first evaluated to an integer (that's where you lose precision), and then this integer is assigned to a.total as a float.

    You therefore need to specify that the operation a.precio * a.iva / 100 has to be done on floats by casting the integer values.

    Change

    a.total=a.precio*a.iva/100;
    

    to

    a.total= ((float)a.precio)*a.iva/100;
    

提交回复
热议问题