My code does not divide well

When I write my code like this, it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  #include <iostream>
  using namespace std;

  int main()
  {
  int height, base;
  float ans;

  cout<<"Enter height and base";
  cin>>height>>base;
  ans= (0.5)*height*base;

  cout<<"Area if triangle is"<<ans;
  }



but when I write it like this, it doesn't:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  #include <iostream>
  using namespace std;

  int main()
  {
  int height, base;
  float ans;

  cout<<"Enter height and base";
  cin>>height>>base;
  ans= (1/2)*height*base;

  cout<<"Area if triangle is"<<ans;
  }


Please tell me why and how can it be done to work using division
The 1 is an int.
The 2 is an int.
If both operands of the operator/ are integers, the result is an integer too. That is the way of the integer division.

1/2 is thus exactly 0.

1.0 / 2 on the other hand implicitly converts the second operand: 1.0 / 2.0 and then performs floating point division, evaluating to double value 0.5.
Topic archived. No new replies allowed.