0

I'm trying to evaluate the following expression in C++. I'm using Visual Studio (current release) if that makes any difference.

#define _USE_MATH_DEFINES
#include <math.h>
#include <iostream>

std::cout << (1.686 * 1000 / (4 / 3) / M_PI / (pow(0.015, 3)) / 3340);

Now when I execute the program the output is:

47608.8

Whereas if I use WolframAlpha the expression is evaluated to: Wolfram's result

I've also tried breaking down each portion of the expression to check if things like the "pow()" function is working correctly or if M_PI is accurate but everything seems to be consistent up until I evaluate everything at once.

Am I missing something, why am I getting an incorrect answer?

I've been looking at this code for quite a while now and I can't seem to figure out what's going on. I'm thinking it might be some sort of precision error?

hichris123
  • 10,145
  • 15
  • 56
  • 70
Paul Warnick
  • 903
  • 2
  • 13
  • 26

1 Answers1

6
(4 / 3)

This sub-expression has two integer arguments, so it will be done with integer math. The result of the division is truncated, so instead of 1.333333f the result is 1.

You can fix it by making one or both numbers floating point constants.

(4.0 / 3.0)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578