简体   繁体   中英

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

I'm new to C and trying to figure out why my code is returning an int to my float variable pounds rather than the float I'm expecting. When testing I can only get my code to return integers. Here's my code and I am using Dev-C++ v4.9.9.2 as per instructed by my professor.

#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;
}

Q: Why is my equation returning an Int number rather than a float?

A: Because every single operand in your expression is being done in integer space.

SUGGESTION: cast your divsor to "float":

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

By default,C throws away the decimal part of the result when the operation deals with just ints.

For example:

float x;

x = 3/2;

X would be equal to 1, instead of 1.5

Since minDrink , minEat , minWalk , and minStand are all int , the equation is returning an int.

You also might need to cast teh #define as float , not sure.

Declare or cast them as floats and you'll get a float in return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM