Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading