简体   繁体   English

如何使用 3 个用户定义函数计算数字的真实平方根

[英]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:计算必须在名为sqRoot的函数中完成,该函数将由main使用以下算法调用:

newValue = 0.5 * (oldValue + (X / oldValue)) 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 sqRoot将需要使用名为absVal的函数找到数字的绝对值,然后该函数将被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:在您的代码段中,您没有展示如何实现absVal() ,这是微不足道的:

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

Assuming that you you know the ternary operator.假设您知道三元运算符。 Otherwise use an if .否则使用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.您发布的main()的实现基本上是一个无限循环,它仅重复计算和打印用户输入的第一个等于或大于 1.0 的数字。 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:我不确定 x >= 1 条件是否是强制性的(微小的值需要更多的迭代)或你的假设以及在负数的情况下你应该做什么(你可以使用 absVal 而不是打印错误) ,但你可以这样写:

#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;然后,在您的sqRoot()实现中,您忘记将变量 x 作为参数传递,以初始化 oldValue 和 newValue,如果执行流程碰巧进入 while 循环,它将在第一个循环后退出,因为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):尝试这样的事情(我使用相对误差而不是绝对差来获得更小的 x 值的更好精度,但需要更多的迭代):

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);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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