【问题标题】:Convert a float to an int将浮点数转换为整数
【发布时间】:2015-05-02 10:15:31
【问题描述】:

我有一个汽车的价格,比如说 10000。我想对这个价格应用 20% 的销售额。

我有一个struct,其中auta->cenafloat

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


【解决方案1】:

如果您要使用%.2f 打印值,则无需进行任何舍入。但是,如果您想在内部舍入该值,则以下方法将起作用。我用%.5f 打印它以表明该值确实发生了变化。

#include <stdio.h>

int main() {
  int discount;
  double price;

  printf("Enter a price: ");
  scanf(" %lf", &price);
  printf("Enter a percentage discount: ");
  scanf(" %d", &discount);

  price *= (100.0 - discount) / 100;  // calculate price after discount
  printf("after discount: %.5f\n", price);

  price = (int)(100 * price + 0.5) / 100.0;
  printf("rounded: %.5f\n", price);
}

我在上面使用double 来保持足够的精度,以证明计算适用于例如 10000 的价格和 20 的折扣。如果您使用 float 进行计算,您将失去足够的精度,四舍五入到最接近的分是没有意义的。无论如何,内部值将是不精确的。

这是使用float的相同代码的变体:

#include <stdio.h>

int main() {
  int discount;
  float price;

  printf("Enter a price: ");
  scanf(" %f", &price);
  printf("Enter a percentage discount: ");
  scanf(" %d", &discount);

  price *= (100.0 - discount) / 100;  // calculate price after discount
  printf("after discount: %.5f\n", price);

  price = (int)(100 * price + 0.5) / 100.0;
  printf("rounded up: %.5f\n", price);
  return 0;
}

【讨论】:

  • 在我的代码还是你的代码中?我没有任何float 变量。
  • 我添加了一个使用float的版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 2019-11-25
相关资源
最近更新 更多