Home > Software engineering >  Why in this simple math problem in c the result is different depending on the place of the float?
Why in this simple math problem in c the result is different depending on the place of the float?

Time:09-27

#include <iostream>; 

using namespace std; 

 /* this one works out when the float of the pi & area are in the end, but when it's in the top it does not work? */

int main() 
{ 

float a, b; 

/* float pi = 3.14 ;

float area = (pi*b*b/4) * ((2*a-b) / (2*a b));  if it's  in here it doesn't work */

cout << "please inter  number \n"; 
cin >> a ;

cout << "please inter  number \n"; 
cin >> b ;

cout << "****\n" ;

float pi = 3.14 ;

float area = (pi*b*b/4) * ((2*a-b) / (2*a b));

cout << area << endl; 

return 0;

}

CodePudding user response:

The area gets set depending on the values currently in the variables used in the expression.

With the expression at the top, neither a nor b have been set to your input values. Instead they will have some arbitrary value, meaning your area will also have some arbitrary value. With the expression after the input of a and b, those values will be the actual values you entered.

You can see this clearer if you place the following code immediately after the calculation (in both situations):

std::cout << "DEBUG: a = " << a << ", b = " << b
    << ", pi = " << pi << ", area = " << area << '\n';
  • Related