Weird problem using decimals in a subtracting loop.

This is a discussion on Weird problem using decimals in a subtracting loop. within the C++ Programming forums, part of the General Programming Boards category; Code: #include <iostream> using namespace std; int main() { double a, b; while (1) { cout << "Enter 1st number ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    1

    Question Weird problem using decimals in a subtracting loop.

    Code:
    #include <iostream>
    using namespace std;
    
    int main() {
      double a, b;
    
      while (1) {
        cout << "Enter 1st number (0 to quit): ";
        cin >> a;
          if (a == 0)
            break;
    
        cout << "Enter 2nd number (0 to quit): ";
        cin >> b;
          if (b == 0)
            break;
    
        while (a >= b)
          a -= b;
    
        cout << "Result: " << a << endl;
      }
    
      return 0;
    }
    Now if I enter, for example, 90 and 3, I get the result 0. But if I try 9 and 0.3 (which should give me an identical response), I get... 1.22125e-15 !

    Can someone explain why this is happening?

    thanks
    --

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,068
    It's a rounding error. In case you don't understand scientific notation, 1.22125e-15 is the equivilent of .00000000000000122 which as you can tell, is very, very close to zero.
    Last edited by SlyMaelstrom; 03-03-2006 at 11:11 PM.
    Sent from my iPad®

  3. #3
    Advanced Novice linucksrox's Avatar
    Join Date
    Apr 2004
    Location
    Michigan
    Posts
    198
    check out the stuff in #include <iomanip> that should most likely help you out with the problem you're having
    "What are all you parallelograms doing here?" - Peter Griffin (to Joe and his wheelchair buddies)

  4. #4
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,068
    ...and if you have real interest in programming, you can check out this link to understand floating-point numbers and why that rounding error occured.

    http://www.petebecker.com/js200006.html
    Sent from my iPad®

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. weird problem with gets();...
    By Huskar in forum C Programming
    Replies: 2
    Last Post: 03-30-2009, 12:58 AM
  2. Replies: 8
    Last Post: 12-09-2008, 11:07 AM
  3. weired problem in while loop
    By avisik in forum C Programming
    Replies: 14
    Last Post: 12-01-2008, 12:41 PM
  4. Problem with a loop
    By wiggsfly in forum C Programming
    Replies: 5
    Last Post: 11-30-2008, 11:45 AM
  5. Problem accessing 3d array in loop...
    By weirdbeardmt in forum C Programming
    Replies: 2
    Last Post: 06-16-2004, 11:43 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21