0

Here is a simple code in c++ and the output is different from what I expected

#include<iostream>
using namespace std;
int main()
{
    double a=0,b=1;
    while(a<b)
    {
        cout<<a<<endl;
        a+=0.1;
    }

}

Output prints the value till 1 instead of stopping at 0.9. Please help me understand the reason behind this.

  • A `double` is only an approximation for most fractional values, since it only has limited precision. So `0.1` is a tiny bit less than mathematical 0.1, so it takes an addition pass through the loop to have `a – Eljay Apr 11 '18 at 01:44
  • Display [more decimals](https://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) to see what the problem is. – Déjà vu Apr 11 '18 at 01:54
  • So how do I overcome this issue?? @Eljay – Satyam Kumar Apr 11 '18 at 01:57
  • @SatyamKumar • change the increment to `a+=1.0;` and change the output to `cout<<(a/10.0)< – Eljay Apr 11 '18 at 02:01
  • Thanks for reply @Eljay but seeing your explanation about being 0.1 being less than mathematical 0.1 I set it to increment by 0.12 and it worked great. Thanks for explanation – Satyam Kumar Apr 11 '18 at 02:09

0 Answers0