lama
lama

Reputation: 1

c++ functions. using loops

I just started learning functions and I am struggling to solve this. Lecturer gave a hint that you have to start calculating from the bottom aka 256 to the top.

This is the formula:

Formula from lecturer

This is the code I have so far (it's incorrect obviously):

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

EDIT:this is what i came up with. When input is 5 answer should be 0,0398732 but this outputs 0,0399363. I can't figure out why

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

Upvotes: 0

Views: 166

Answers (1)

Russell Loomes
Russell Loomes

Reputation: 11

What you have here is a recursive function, meaning that the function essentially calls itself.

This function can be expressed as:

r = x2 + (n / d)

d is a divisor, in the first instance, it is x2. In subsequent calls, it is the result from the previous step. Even though the problem itself is recursive, it's simple enough to do in an iterative loop instead:

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

EDIT: Also as stated in the comments from other users, you have initialised X as int when it should be a double, so that the divisions don't return an int.

You have ats as a double, so you were on the right track, but it is getting an int returned from your function.

Upvotes: 1

Related Questions