为什么我的等式返回 Int 数字而不是浮点数? (C, 开发-C++)

Why is my equation returning an Int number rather than a float? (C, Dev-C++)

我是 C 的新手,我想弄清楚为什么我的代码 return 将 int 转换为我的 float 变量 pounds 而不是我期望的 float。测试时,我只能将我的代码设为 return 整数。这是我的代码,我按照教授的指示使用 Dev-C++ v4.9.9.2。

#include <stdio.h>

#define WALK_CAL 5
#define STAND_CAL 2
#define DRINK_CAL 20
#define FOOD_CAL 40
#define CALS_PER_POUND 3500

main(){
   int minWalk;
   int minStand;
   int minDrink;
   int minEat;
   float pounds;

   printf("How many minutes were you walking? \n");
   scanf("%d", &minWalk);

   printf("How many minutes were you standing? \n");
   scanf("%d", &minStand);

   printf("How many minutes were you drinking? \n");
   scanf("%d", &minDrink);

   printf("How many minutes were you eating? \n");
   scanf("%d", &minEat);

   pounds = ((((minDrink*DRINK_CAL)+(minEat*FOOD_CAL))-((minWalk*WALK_CAL)+(minStand*STAND_CAL)))/CALS_PER_POUND)*-1;

   if(pounds >= 0){
      printf("You lost %.3f pounds today! \n", pounds);
   } else {
      printf("Weight lost is %.3f pounds. \n", pounds);
   }

   system("pause");

   return 0;
}

因为 minDrinkminEatminWalkminStand 都是 int,所以等式是 return 一个整数。

您可能还需要将 #define 转换为 float,不确定。

将它们声明或转换为浮点数,您将在 return 中得到一个浮点数。

默认情况下,当运算仅处理整数时,C 会丢弃结果的小数部分。

例如:

float x;

x = 3/2;

X 等于 1,而不是 1.5

问:为什么我的等式返回 Int 数字而不是浮点数?

A:因为表达式中的每个操作数都是整数 space。

建议:将除数设为 "float":

pounds = (
  (
    ( (minDrink * DRINK_CAL) +  (minEat * FOOD_CAL) ) - 
    ( (minWalk * WALK_CAL) +  (minStand * STAND_CAL) ) 
  ) / (float)CALS_PER_POUND ) * -1 ;