gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:52 27 4
gpt4 key购买 nike

我需要一些帮助和一些关于去哪里的提示对于编程作业,我必须编写一个程序来计算用户输入的数字的平方根,并且有一定的要求。

  1. ma​​in 请求数字并显示它,在一个循环内运行,以便用户可以在不关闭它的情况下重复该程序

  2. 计算必须在名为 sqRoot 的函数中完成,该函数将由 ma​​in 使用以下算法调用:

新值 = 0.5 * (旧值 + (X/旧值))

  1. sqRoot 需要使用名为 absVal 的函数找到数字的绝对值,然后 sqRoot

我什至不知道从哪里开始这样的程序。但是,这是我到目前为止所拥有的:

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

我只是纠结于下一步该做什么以及如何正确编写程序。感谢您的帮助和提示!

最佳答案

在您的代码片段中,您没有展示如何实现 absVal(),这很简单:

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

假设您知道三元运算符。否则使用 if

您发布的 main() 的实现基本上是一个无限循环,它只重复计算和打印用户输入的第一个等于或大于 1.0 的数字。我想这不是你要的

我不确定 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
}

然后,在 sqRoot() 的实现中,您忘记将变量 x 作为参数传递,以初始化 oldValue 和 newValue,如果执行流程恰好进入 while 循环,它将退出在第一个循环之后,因为 oldValue = newValue; 在条件之前被评估。尝试这样的事情(我使用相对误差而不是绝对差来获得更好的精度 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;
}

希望对您有所帮助。

关于c++ - 如何使用 3 个用户定义函数计算数字的真平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36455692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com