shreyanshd
shreyanshd

Reputation: 21

Why doesn't C++ return a double on division?

I am trying to divide two integers and want the exact answer in double. My code works fine for small values:

#include<iostream>
using namespace std;
int main()
{
    int max = 100;
    int min = 10;
    int n = 8;
    double gap = (max-min)/(double)(n-1);
    cout<<gap<<endl;
}

This prints 12.8571

But when I run this:

#include<iostream>
using namespace std;
int main()
{
    int max = 99404748;
    int min = 925679;
    int n = 240;
    double gap = (max-min)/(double)(n-1);
    cout<<gap<<endl;
}

It prints 412046 while the actual answer is 412046.3138

What is the reason for this behaviour? Also, how can I fix it?

Upvotes: 1

Views: 171

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Everything with your double value is fine. The result you see is just a matter of how it's represented in the std::ostream.

Use the fixed and setprecision() I/O manipulators, to change the behavior of the representation:

#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
    int max = 99404748;
    int min = 925679;
    int n = 240;
    double gap = (max-min)/(double)(n-1);
    cout << fixed << setprecision(4) <<gap<<endl;
         // ^^^^^    ^^^^^^^^^^^^^^^
}

Live Demo

Upvotes: 7

Related Questions