0

In C++, why does dividing 2 floating point numbers via 2 different mechanisms (inline and via a function call) output different results as per below?

After the following computations where 5 is divided into 4, f1 = 0 and f2 = 0.8.

#include <iostream>
using namespace std;

int main() {
    float f1 = 4 / 5;
    float f2 = FloatDivision(4, 5);
    cout << "f1 equals " << f1 << endl;
    cout << "f2 equals " << f2 << endl;
    cin.ignore();
}

float FloatDivision(float f1, float f2) {
    if (f2 != 0) {
        return f1 / f2;
    } else {
        cout << "Error: The denominator cannot be zero" << endl;
        return 0;
    }
}
Guru Josh
  • 566
  • 8
  • 16
  • 8
    `4 / 5` is integer division. Try `4.0 / 5.0` instead. – Bo Persson Jul 02 '18 at 05:00
  • 1
    You are using integer division which reproduce the integer. Use can try (float) 4 / 5 to get the float. – Sumeet Jul 02 '18 at 05:03
  • 1
    As @BoPersson denoted already, integer division - `4.0/5.0` is double division, though, so if you *insist* on floats, you'd have to write `4.0f/5.0f`... – Aconcagua Jul 02 '18 at 05:52
  • 1
    Possible duplicate of [Integer division always zero](https://stackoverflow.com/questions/9455271/integer-division-always-zero) – phuclv Jul 02 '18 at 06:48

2 Answers2

3

4 / 5 is integer division. You have defined them as such. Whereas in your division function you defined them as floats.

For f1, try

float f1 = 4.0 / 5.0;
bcr
  • 950
  • 8
  • 28
2

in case of

  float f1 = 4 / 5;

It is integer division which results in 0 and then it is converted to float and it remains 0.

in case of function call DivFloat, it takes float arguments, hence 4 and 5 are first converted to float and then division happens. Hence results 0.8.

code707
  • 1,663
  • 1
  • 8
  • 20