0

The output is supposed to be small decimal value. I've gone through it and it seems right, but the output keeps coming out as zero. For example, if I entered 120, 230, 20 and 15 respectively, it should spit out 0.017 , but I still get zero.

#include <stdio.h>

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

int main(void) {

    int walking_min, standing_min;
    int drinking_min, eating_min;
    float end_calories;

    //Get User Input
    printf("How long were you walking (in minutes) ?\n");
    scanf("%d", &walking_min);

    printf("How long were you standing (in minutes) ?\n");
    scanf("%d", &standing_min);

    printf("How long were you drinking (in minutes) ?\n");
    scanf("%d", &drinking_min);

    printf("How long were you eating (in minutes) ?\n");
    scanf("%d", &eating_min);

    //Evaluate User Input
    end_calories = ( ( (WALK_CAL*walking_min) + (STAND_CAL*standing_min) - (DRINK_CAL*drinking_min) - (FOOD_CAL*eating_min) ) / CALS_PER_POUND );

    //Output Final Value
    printf("You lost %.3f pounds today!\n", end_calories);

    return 0;

}

Thanks in advance!

beginner
  • 31
  • 5
  • Integer division != Floating point division. – WhozCraig Aug 31 '16 at 01:14
  • When you divide two integers, you get an integer (rounding towards zero). It doesn't magically change this if you then go on to assign this integer to a float. – M.M Aug 31 '16 at 01:14

1 Answers1

3

What you are seeing is integer truncation. The decimal portion of the end calories amount is being cut off. One way around this is to divide by a floating point number, i.e. divide by:

(CALS_PER_POUND * 1.0)

Or, if you don't mind changing your constants, you can use:

#define CALS_PER_POUND 3500.0f
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360