【发布时间】:2015-05-02 10:15:31
【问题描述】:
我有一个汽车的价格,比如说 10000。我想对这个价格应用 20% 的销售额。
我有一个struct,其中auta->cena 是float。
int year, i, n=0, pocet=1, sale;
scanf(" %d", &year);
scanf(" %d", &sale);
for(i=1; i<=pocet; i++){
if(year == auta->rok){
++n;
pocet++;
auta->cena *= ((float)(100 - sale) / 100); //calculate price after 20% sale
//temp = ((int)(temp * 100 + 0.5)) / 100.0; //use this formula to round up final price, it doesnt work, I get 0.00
printf("%.2f\n", auta->cena);
}
auta = auta->dalsi;
}
我不擅长转换——谁能给我解释一下,好吗?我该怎么办?
【问题讨论】:
-
您确定在四舍五入之前得到正确的值吗?
-
是的,直到四舍五入都可以使用
-
您可能希望在
temp *= ((float)(100 - sale) / 100)之后打印temp的值。这可能不是你所期望的...... -
我更新了代码,但仍然没有改变逻辑,在 20% 的销售后我真的得到了正确的价格。
-
((int)(temp * 100 + 0.5)) / 100.0 应该是 (int)((temp * 100 + 0.5)) / 100.0) ...当将 int 转换为 float 时,它应该做你做的第一件事,从 float 到 int 最后。
标签: c floating-point type-conversion floating-point-precision floating-point-conversion