Thread: Function calling before loop ends

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    17

    Function calling before loop ends

    Ok I have tried a few ways to get this loop to terminate before using the ending variable in the function but I cannot seem to figure it out. This is just my latest attempt. I want this program to end when the user enters 0 but it always returns a square root for 0 (which of course is 0) before terminating. Did I really forget how to do this much while on vacation?

    Code:
    #include <iostream>
    #include <cmath>
    using namespace std;
    void wierdsquareroot (double x)
    {
    	cout << "The square root is " << sqrt(x) << endl;
    }
    int main ()  // Program calculates the square root of a number
    {
    	double num;
    	do
    	{
    		if (num != 0)
    		{
    			cout << "Enter a number (a double): "; cin >> num;
    			wierdsquareroot (num);
    		}
    	}while (num != 0);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You need to read the input before you do the check for num != 0.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    17
    As soon as I posted I noticed my input was inside the if statement and that is why everything was thrown off.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    17
    What laser said

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A Function Calling a Function
    By dac in forum C++ Programming
    Replies: 8
    Last Post: 12-17-2006, 04:10 PM
  2. Calling a function...
    By Taka in forum C Programming
    Replies: 6
    Last Post: 10-02-2006, 01:04 AM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM