c++ - c++ 函数。使用循环
问题描述
我刚开始学习函数,我正在努力解决这个问题。讲师提示您必须从底部开始计算,即 256 到顶部。
这是公式:
这是我到目前为止的代码(显然不正确):
#include <iostream>
using namespace std;
int funkc(int x);
int main() {
double ats;
int x;
cout << "enter x value" << endl;
cin >> x;
ats = funkc(x);
cout << ats << endl;
}
int funkc(int x){
int n;
int o;
int a;
n=256;
while(n >= 2){
n = n/2;
o = x*x + (n/(x*x));
a = x*x + (n/o);
o = a;
}
return a;
}
编辑:这就是我想出的。当输入为 5 时,答案应为 0,0398732,但输出为 0,0399363。我不知道为什么
#include <iostream>
#include <cmath>
using namespace std;
double o;
double a;
double Y(double x);
int main() {
double x;
cout << "enter x value" << endl;
cin >> x;
cout << Y(x)<<endl;
}
double Y(double x){
for(int n=256; n>1; n/=2){
o=x*x+(n/(x*x));
a=x*x+((n/2)/o);
o=a;
}
return 1/o;
}
解决方案
您在这里拥有的是一个递归函数,这意味着该函数本质上是调用自身。
这个函数可以表示为:
r = x2 + (n / d)
d 是一个除数,在第一个例子中,它是 x2。在随后的调用中,它是上一步的结果。即使问题本身是递归的,它也很简单,可以在迭代循环中完成:
double findY(double x)
{
// let's pre-compute x*x since we reuse it a lot
double x2 = x * x;
// first step, the divisor is x2, so we will set that as initial value
double divisor = x2;
// we can use a for loop since we are looping from 256 to 1, but use divide instead of ++n
for (int n = 256; n > 1; n /= 2)
{
// our recursive function as explained above
// the answer is assigned to divisor and used in the next loop
divisor = x2 + (n / divisor);
}
// EDIT: forgot that we need 1/answer to get the final result
return 1.0/divisor;
}
编辑:也如其他用户的评论中所述,您已将 X 初始化为 int,而它应该是双精度数,这样分区就不会返回 int。
您将 ats 作为双精度数,因此您走在正确的轨道上,但是它正在从您的函数返回一个 int 。
推荐阅读
- reinforcement-learning - 同时拥有状态价值函数和动作价值函数有什么用?
- java - Java 8 Streams,将一个元素放在列表的顶部,然后按名称的字母顺序排序
- c# - 为 .net 库创建一个 helplink 属性以显示在我的库作为参考添加的 Visual Studio 中
- javascript - 以下 queueMicrotask polyfill 如何回退到使用 setTimeout?
- javascript - 如何停止 setInterval
- .net - .NET Core 版本的 MSBuild 不支持任务工厂“CodeTaskFactory”
- python - 我的网页抓取输出显示的是汉字
- http - 对于输入的旧密码不正确的更改密码请求,正确的 HTTP 响应是什么?
- javascript - 赛普拉斯:我们如何在赛普拉斯中使用不记名令牌编写 GET 请求?
- javascript - 通过动画打开或关闭 div