1

I have been trying to print decimals by storing the variables into float and double but I am not getting the desired output. what don't I understand about these data types?

Following is my code:

int main(){
    double s = 0;
    float r = 1 / 4;
    cout << r << endl;
    cout << pow((1 - s), 2) << endl;
    cout << (2 + s) << endl;
    cout << (1 / 4) * (pow((1 - s), 2)) * (2 + s) << endl;
    return 0;
}

Output:

0
1
2
0

The first line should be 0.25 and the last should be 0.5.

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
user6771484
  • 81
  • 2
  • 12

1 Answers1

2

You are doing integer math. Integer one divided by integer four is rounded down to zero.

You need to tell the compiler that your number literals are floating point values.

float r = 1.0 / 4.0;
cout << r << endl;
cout << pow((1.0 - s), 2) << endl;
cout << (2.0 + s) << endl;
cout << (1.0 / 4.0) * (pow((1.0 - s), 2)) * (2.0 + s) << endl;
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40