简体   繁体   中英

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?

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.

When you give n=3 , (-10/((n-1)*(-2))) gives you (-10/((3-1)*(-2))) = 2.5 . My suggestion would be return (10/((n-1)*2)) * sign(n) , where sign(n) return 1 if n is even, and return -1 otherwise.

I think your problem has a really nice & easy recursive solution:

double count(int n){
    if (n <= 1) return -10;
    return count(n - 1)*-0.5;
}

Example call:

#include <iostream>
#include <iomanip>

int main(){
    for (int i = 1; i < 20; ++i){
        std::cout << std::setw(15) << count(i) << std::endl;
    }

    return 0;
}

output:

            -10
              5
           -2.5
           1.25
         -0.625
         0.3125
       -0.15625
       0.078125
     -0.0390625
      0.0195313
    -0.00976563
     0.00488281
    -0.00244141
      0.0012207
   -0.000610352
    0.000305176
   -0.000152588
   7.62939e-005
   -3.8147e-005

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM