in the order of mathematical hierarchy gives me 410 and in the compilation of the code gives me 400 what should be the error?

1
#include <iostream>
#include <conio.h>
using namespace std;
 main() 
{ 
  double  x = ( 4 * 5 * ( 7 + ( 9 * 3 / ( 2 ) ) ) ) ;
  cout<<"el resultado de x es: "<<x;// el resultado es 400

  getch();  
}
    
asked by edwin_ucli 22.11.2016 в 00:55
source

1 answer

4

All your operations are with integers, with which all the results are integers.

That means, that by dividing 27 / 2 you'll get 13 ( 13.5 is not an integer). So:

  • 9 * 3 = 27

  • 27/2 = 13

  • 7 + 13 = 20

  • 20 * 20 = 400

The simplest thing is to convert some number (the most internal you have), to floating point, that makes the arithmetic happen with floating point.

For example, you pass 3 to 3.0 , and you have left:

  • 9 * 3.0 = 27.0

  • 27.0 / 2 = 13.5

  • 7 + 13.5 = 20.5

  • 20 * 20.5 = 410.0

Another option is to make sure that the divisors are always floating numbers, since the source of the error is to use the entire division instead of the floating-point division.

    
answered by 22.11.2016 / 01:00
source