2

Following code (in c++) works fine for value less than 6 digit but it start to lose precision when dividing more than 6 digits. Code:

double number;
cin>>number;
double result = number / 2.0L;
cout<<result<<endl;

Above code gives 61729.5 for 123459 which is correct. But for 1234569 it outputs 617284 which is wrong. Can anyone please explain what's happening here.

Thanks.

Fe2O3
  • 6,077
  • 2
  • 4
  • 20
  • Probably only the output is rounded. Subtract 610000 and see what happens. – Sebastian Oct 11 '22 at 07:52
  • 8
    use [`std::setprecision`](https://en.cppreference.com/w/cpp/io/manip/setprecision): `std::cout << std::setprecision(10) << result << std::endl;` [Demo](https://godbolt.org/z/rf61bv76z). – Jarod42 Oct 11 '22 at 07:53
  • 1
    Wrong duplicate, it's totally unrelated. Voted to reopen. – Jabberwocky Oct 11 '22 at 07:55
  • [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Jesper Juhl Oct 11 '22 at 07:55
  • @DevSolar Is 32-bit double valid C++ at all? – Sebastian Oct 11 '22 at 07:58
  • 3
    @DevSolar I can reproduce the issue on my x86_64 platform which has 64 bit doubles. It's not a floating point precision issue but a display issue. – Jabberwocky Oct 11 '22 at 07:58
  • @Sebastian: Not all platforms need to be fully conforming. If you don't have a 64-bit FP on your machine, you don't... but it seems I was mistaken anyway, so the question is academic. – DevSolar Oct 11 '22 at 08:08

1 Answers1

6

Your issue is a display issue, increase precision with std::setprecision (the default precision, as established by std::basic_ios::init, is 6):

std::cout << std::setprecision(10) << result << std::endl;

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Got this error when submitting my code to codeforces. Does this affects online judges or my system only. Thanks for answering – deepak dubey Oct 12 '22 at 06:27
  • Default of 6 is not system specific, from [`std::basic_ios::init`](https://en.cppreference.com/w/cpp/io/basic_ios/init). – Jarod42 Oct 12 '22 at 09:29