将float转换为int

时间:2015-05-02 10:15:32

标签: c floating-point type-conversion floating-point-precision floating-point-conversion

我有车的价格,让我们说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;
}

我不擅长转换 - 请有人向我解释,拜托吗?我应该怎么做呢?

1 个答案:

答案 0 :(得分:0)

如果您要使用%.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;
}