c++ - 简单的平方根
问题描述
我在 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;
}
上面的代码给出了正确的输出。我只是提高了精度。您正在使用蛮力方法找到根。您如何使用一些复杂的方法,例如Newton's Method。
推荐阅读
- javascript - 有没有办法改变 D3.js 折线图上的颜色线?
- firebase - Firebase 身份验证和计费订阅
- c++ - 从文件 c++ 创建一个字符串向量
- java - Couchbase 中的自动增量
- excel - 使用带有动态变量和多个工作表的 INDEX / MATCH 编写 VBA
- ios - SwiftUI 辅助功能 VoiceOver 焦点问题
- python - 遍历数据框会更改列结构
- c# - 时间:2019-05-10 标签:c#repater from JSON without class
- mongodb - 在 $cond 中使用数组字段
- php - WhereHas 有条件