Black_Knight's blog

By Black_Knight, 11 years ago, In English

The Following Code should output "Happy Coding" after certain operations, but it is never printed. When n=0.01 and the statement n-=0.01 executes, it prints 5.52024e^-014. Can anyone explain why it occurs and what the remedy is??

#include <iostream>
#include <cmath>
#include <conio.h>
using namespace std;
int main()
{
    double n;
    n=45.65;
    while(n!=0.00)
    {
        n-=0.01;
        cout<<n<<" "<<endl;
    }

    cout<<"Happy Coding"<<endl;
    return 0;
}

Thanks in Advance.

  • Vote: I like it
  • +5
  • Vote: I do not like it

| Write comment?
»
11 years ago, # |
  Vote: I like it +1 Vote: I do not like it

remedy:

repalce != with !eq(n, 0.00)

double eps = 1e-10; bool eq(double a, double b) { return abs(a-b) < eps;}

»
11 years ago, # |
  Vote: I like it +7 Vote: I do not like it

http://en.wikipedia.org/wiki/IEEE_floating_point

Good place to start, if you really want to learn about it.