数字序列

Sequence of numbers

本文关键字:字序 数字      更新时间:2023-10-16

我需要创建程序,在输出中我将获得第 n 个数字或序列。序列如下所示:

(-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;
}
对我来说,每个想法对我来说都很好,当我给程序 1 时,它给出 -10,当我给 2 时,它返回 5,但在 3 上它给出 2.5,

而不是 -2.5,在 4 上它给出 1。(6(,这对我来说没有意义。这段代码哪里有错误?

针对您的问题的高效(优化代码(代码是:

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

注意:冗余是由于代码中的分支而发生的。最好尽可能尝试编写直线代码(没有太多分支(。

当你给n=3时,(-10/((n-1)*(-2)))给你(-10/((3-1)*(-2))) = 2.5。我的建议是返回(10/((n-1)*2)) * sign(n),如果 n 是偶数,则sign(n)返回 1,否则返回 -1。

我认为你的问题有一个非常好和简单的递归解决方案:

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

调用示例:

#include <iostream>
#include <iomanip>
int main(){
    for (int i = 1; i < 20; ++i){
        std::cout << std::setw(15) << count(i) << std::endl;
    }
    return 0;
}

输出:

            -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