szymoneiro szymoneiro - 23 days ago 8
C++ Question

Sequence of numbers

I need to create program, where in output I'll get the n-th number or sequence. Sequence looks like that:

(-10, 5, -2.5, 1.25, -0.625...)

#include <iostream>

using namespace std;

double count (double n)
{
if (n==1)
return -10;
else
return (-10/((n-1)*(-2)));
}

double n;

main()
{
cout<<"n? : ";
cin>>n;
cout<<count(n);
return 0;
}


For me everythink looks good for me, when I give to the program 1, it gives -10, when I give 2, it gives back 5, but on 3 it gives 2.5, not -2.5, on 4 it gives 1.(6), which doesn't make sense for me. Where's mistake in this code?

Answer

An efficient(optimized code) code for your question would be:

#include <iostream>
#include<math.h>
using namespace std;

double count (double n)
{
  double x = pow(2, n - 1);      //calculate the divisor
  return pow(-1, n) * (10 / x);  // divide 10 with divisor followed by assigning it  a sign
}

int main()
{
  int n;
  cout<<"n? : ";
  cin>>n ;
  cout<<count(n) << endl;
  return 0;
}

Note: Redundancy occurs due to branching in your code. Better try to write straight-line code(without too many branchings) wherever possible.