0

sorry if this is an obvious question but I just started learning computer science.

I have to print the results of this with 14 decimal places so I did so by using %.14f in a printf statement. All of the other variables are integers

double caloriesBurnedW = 0.0175 * 4 * (weight/2.2) * walkingTime; 
double caloriesBurnedR = 0.0175 * 10 * (weight/2.2) * runningTime;
double caloriesBurnedMC = 0.0175 * 8 * (weight/2.2) * mountainClimberTime;

The outputs I get are

  • 286.36363636363640
  • 114.54545454545455
  • 229.09090909090910

but they should be

  • 286.3636363636364
  • 114.54545454545456
  • 229.09090909090912
  • If you need precision use `BigDecimal` . – PM 77-1 Jan 19 '22 at 21:30
  • Also read https://stackoverflow.com/questions/588004/is-floating-point-math-broken – OldProgrammer Jan 19 '22 at 21:30
  • @PM77-1 I tried doing this but I still get the same values `BigDecimal caloriesBurnedW = BigDecimal.valueOf(0.0175 * 4 * (weight/2.2) * walkingTime); BigDecimal caloriesBurnedR = BigDecimal.valueOf(0.0175 * 10 * (weight/2.2) * runningTime); BigDecimal caloriesBurnedMC = BigDecimal.valueOf(0.0175 * 8 * (weight/2.2) * mountainClimberTime); ` – username123 Jan 19 '22 at 21:36
  • Then your "*should be*" numbers are wrong. – PM 77-1 Jan 19 '22 at 21:37
  • @PM77-1 They're straight from the assignment sheet though. It says that the program "must display the same information with the same format" – username123 Jan 19 '22 at 21:39
  • 1
    `286.3636363636364` has 13, not 14 decimals. The person who wrote the exercise appears to have done a basic `System.out.println(caloriesBurnedW);` and it just happened to result in this number of decimals (for weight=150, walkingTime=60). I would try that instead of direct formatting. I don't think this would have been an issue if the exercise author was more familiar with floating point numbers. – that other guy Jan 19 '22 at 21:51

1 Answers1

0

Instead of dividing the weight by 2.2, I created a variable

kgWeight = weight * (1/2.2) 

That resolved the issue for some reason