简单的平方根

Simple Square Rooter

本文关键字:平方根 简单      更新时间:2023-10-16

我在C++类之间,所以为了保持练习,我写了一个程序来寻找根源。

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double input;
bool done = false;
static double check;
while (done == false)
{
cout << "what number to root? ";
cin >> input;
bool foundRoot = false;
check = input;
while (foundRoot == false)
{
if (check * check == input || check*check < input)
{
foundRoot = true;
//done = true;
}
else
{
check = check - .00001;
}
}
cout << "The root of " << input << " is " << setprecision(7) << check << endl;
}
}

这个程序似乎为任何平方测试返回正确的值(即使是非完全的(;但是输入"25"返回4.9999~。为什么?

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double input;
bool done = false;
static double check;
cout << "what number to root? ";
cin >> input;   
bool foundRoot = false;
check = input;
while (!foundRoot)
{
if (check * check <= input)
{
foundRoot = true;
}
else
{
check = check - .000001;
}
}
cout << "The root of " << input << " is " << setprecision(7) << check << endl;
}

上面的代码给出了正确的输出。我只是提高了精度。您正在使用蛮力方法来查找根。你使用一些复杂的方法怎么样,比如牛顿方法。