数字序列
Sequence of numbers
我需要创建程序,在输出中我将获得第 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
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 当套接字连接断开时检测C/C++Unix
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 我怎么不能按课程代码的降序对数字进行排序
- 如何安全地将有符号字段从uint32_t提取到有符号数字(int或uint32_t)中
- 如何检查字段中输入的数字是否重复
- 在编译时根据字节序定义位字段
- 查找升序列表中降序的第一个和最后一个数字
- 用户定义字面值如何与数字分隔符一起使用
- 我将ASCII字转换成数字,但我一直试图解码它们.如何转换1=a, 2=b, 28=ab等?(psudeocode好)
- 一个数字和字段宽度的格式化输出,C++标准在哪里说明它
- linux/freebsd中的套接字描述符是否保证具有几乎连续的或可比较的数字?
- 概率以数字降序递增
- 使用constexpr将数字转换为字符串字面值