1

I am trying to do a simple calculation : ( (45/100) - (20+50)/200 )*(10+5)

I am expecting the answer to be 1.5 but when the programme is compiled , it shows 0.

Can someone figure this out for me

#include <iostream>
using namespace std;

int main()
{
   float   CivIndex = ( (45/100) -  (20+50)/200 )
                  *(10+5);

   cout<<CivIndex; // expect 1.5 but getting 0
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
Computernerd
  • 7,378
  • 18
  • 66
  • 95
  • You are doing [integer division](http://mathworld.wolfram.com/IntegerDivision.html). You need to specify float constants, e.g. `45.0f / 100.0f`. – i_am_jorf Oct 07 '13 at 16:40

7 Answers7

5

Integer division!

(45 / 100) equals 0 when evaluated as an integer, not 0.45 as you'd been hoping.

Make either numerator or denominator a float to get the expected result:

(45.0 / 100)

James Cronen
  • 5,715
  • 2
  • 32
  • 52
3

What you are doing is integer division, and integer division rounds the result to the closest integer. To correct your code, change it to:

#include <iostream>
using namespace std;

int main()
{
   float   CivIndex = ( (45.0/100.0) -  (20.0+50.0)/200.0 )
                  *(10.0+5.0);

   cout<<CivIndex; // expect 1.5 but getting 0
}

Note: not all .0 are needed, but just put them to be sure.

Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
2

You are doing integer division.

Specify it as float constants

 float   CivIndex = ( (45./100) -  (20+50)/200. )*(10+5);
                        ^ Notice decimal points^
P0W
  • 46,614
  • 9
  • 72
  • 119
2

All your constants are ints, therefore, the compiler is doing integer math. 45/100 as an int is 0. So is 70/200. 0 - 0*15 = 0. You need to tell the compiler that your constants are floats: 20f, or 20.0 would both work. (For each operation, if at least one constant is a float, the operation will be treated as floating point math.)

neminem
  • 2,658
  • 5
  • 27
  • 36
2

In C and several other languages diving two integers result in an integer (integral division). That is 45 / 100 in your code will result in 0 instead of the expected 0.45

The fix is simple: convert one of the operands to floating point.

float   CivIndex = ( (45/100.0) -  (20+50)/200.0 )
              *(10+5);
Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
1

You are hoping the integer division as 0.45 but that is actually 0

Try to change this as:

 float   CivIndex = ( (45.0/100) -  (20.0+50.0)/200 )
              *(10+5);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You are essentially evaluating an expression containing only integers. So the result will be an integer. You can use casts on the final result of the integer expression. e.g..

int a=20;float b; b=(float)a;cout<<"b: "<<b;

Please confirm the syntax.

Or as stated above, you can also make one of you operands as a float/double(if your requirement permits).

Dave Hogan
  • 3,201
  • 6
  • 29
  • 54