Different outcomes when adding a ".0" to the divisor

Can someone explain why the outcome is different in my code?

I was trying out the easy problems in Codechum when I encountered something confusing, this was my code.

#include <iostream>
#include <iomanip>

using namespace std;

int num1, num2, num3;
double avg;

int main(){

    cout << "Enter three numbers: ";
    cin >> num1 >> num2 >> num3;

    avg = (num1+num2+num3) / 3;

    cout << setprecision(2) << fixed << "Average of the three numbers: " << avg; 

    return 0;
}

I was confused as to why I only got 3 out of the 6 test cases correct, I looked everywhere on my code and I still had no idea so I viewed the solution and noticed that there’s a ".0" on the divisor of the solution code, so I tried it and it worked on all 6 test cases. This was my code after

#include <iostream>
#include <iomanip>

using namespace std;

int num1, num2, num3;
double avg;

int main(){

    cout << "Enter three numbers: ";
    cin >> num1 >> num2 >> num3;

    avg = (num1+num2+num3) / 3.0;

    cout << setprecision(2) << fixed << "Average of the three numbers: " << avg; 

    return 0;
}

I might have missed something so small or overlooked a very simple idea…

>Solution :

In this expression:

(num1+num2+num3) / 3

Both operands of the division operator have integer type, so integer division is performs which truncates any fractional part. While is this expression:

(num1+num2+num3) / 3.0

The constant 3.0 has floating point type, and since this is one of the operands of the division operator, floating point division occurs which retains any fractional portion.

Leave a Reply