首页 > 解决方案 > 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;
} 

标签: c++

解决方案


您在这里拥有的是一个递归函数,这意味着该函数本质上是调用自身。

这个函数可以表示为:

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 。


推荐阅读