简体   繁体   中英

How to calculate the true square root of a number with 3 user-defined functions

I need a bit of help and some tips on where to go For a programming assignment, I have to write a program that calculates the square root of the number that the user inputs and there are certain requirements.

  1. The main asks for the number and displays it, operates inside a Loop so that the user can repeat the program without closing it

  2. The calculation has to be done in a function called sqRoot which will be called by main using the algorithm:

newValue = 0.5 * (oldValue + (X / oldValue))

  1. sqRoot will need to find the absolute value of the number with a function named absVal which will then be called by sqRoot

I dont even know where to start with a program like this. But, this is what i have so far:

#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;

double sqRoot();
double absVal();
int i = 0;
double X;

int main()
{
   sqRoot = sqrt(X);
   double X;

   // Calculations

   cout << "Please enter a number: ";
   cin >> X;

   while (X <= 0)
   {
      cout << "*** Error: Invalid Number! *** " << endl;
      cout << "Please enter a number: ";
      cin >> X;
   }
   while (X >= 1)
   {
      cout << "The Square Root is: " << sqRoot << endl;
   }
}

double sqRoot ()
{
   double newValue;
   double oldValue ;
   while (abs(newValue - oldValue) > 0.0001)
   {
      newValue = 0.5 * (oldValue + ( X / oldValue));
      oldValue = newValue;
      cout << " The square root is: " << newValue << endl;
   }
   return (newValue);
}

I'm just stuck with what to do next and how to properly write the program. Thank You for the help and tips!

In your snippet you don't show how you implement absVal() , which is trivial:

double absVal( double x )
{
    return  x < 0.0 ? -x : x;
}

Assuming that you you know the ternary operator. Otherwise use an if .

The implementation of main() you posted is basically an infinite loop which calculates and prints repeatedly only the first number equal or greater then 1.0 that the user inputs. That's not what you are asked for, I think

I'm not sure if the x >= 1 condition is mandatory (tiny values requires more iterations) or an assumption of yours and what you are supposed to do in case of a negative number (you can use absVal instead of printing an error), but you can write something like this:

#include <iostream>
// #include <cmath>         <-- you are not supposed to use that
// #include <cstdlib>       <-- why do you want that?
// using namespace std;     <-- bad idea

using std::cin;
using std::cout;

double absVal( double x );
double sqRoot( double x );

int main()
{
    double num;

    cout << "This program calculate the square root of the numbers you enter.\n"
         << "Please, enter a number or something else to quit the program:\n";

    // this will loop till std::cin fails
    while ( cin >> num )
    {
        if ( num < 0.0 ) {
            cout << "*** Error: Invalid input! ***\n"
                 << "Please enter a positive number: ";
            continue;
        }

        cout << "The square root of " << num << " is: " << sqRoot(num);
        cout << "\nPlease enter a number: ";
    }

    return 0;       // you missed this
}

Then, in your implementation of sqRoot() you forgot to pass the variable x as a parameter, to initialize oldValue and newValue and if the flow of execution happens to enter the while loop it will exit after the first loop because oldValue = newValue; is evaluated before the condition. Try something like this (I used the relative error instead of the absolute difference to gain better precision with small values of x at the cost of more iterations):

double sqRoot(double x)
{
    const double eps = 0.0001;
    double newValue = 0;        
    double oldValue = x;

    while ( oldValue != 0.0 )
    {
        newValue = 0.5 * (oldValue + (x / oldValue));

        // check if the relative error is small enough
        if ( absVal(newValue - oldValue) / oldValue  <  eps )
            break;

        oldValue = newValue;
    }

    return newValue;
 }

Hope it helped.

Just a few corrections

#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;

double sqRoot(double X);

int main()
{
    double X;

    // Calculations

    cout << "Please enter a number: ";
    cin >> X;

    while (X <= 0)
    {
        cout << "*** Error: Invalid Number! *** " << endl;
        cout << "Please enter a number: ";
        cin >> X;
    }
    while (X >= 1)
    {
        cout << "The Square Root is: " << sqRoot(X) << endl;
    }
}

double sqRoot(double X)
{
    double newValue = 0;
    double oldValue = X;
    while (true)
    {
        newValue = 0.5 * (oldValue + (X / oldValue));
        if (abs(newValue - oldValue) < 0.0001)
            break;
        oldValue = newValue;
        //cout << " The square root is: " << newValue << endl;
    }
    return (newValue);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM