C++序列计算器x_{n+1} = f(x_n),数学函数有问题
c++ sequence calculator x_{n+1} = f (x_n), trouble with math functions
代码示例
#include <iostream>
using namespace std;
//whitespace package
#include <iomanip>
#include <math.h>
using std::setw;
int main () {
// n is an array of 101 integers
double n[ 101 ];
double exponent=3;
double fraction=1/7;
// initialize elements of array n to 0
for ( int i = 1; i < 100; i++ ) {
n[ i ] = 0;
}
//what is input 1?
cout << "Enter x_1" << endl;
cin >> n[1];
//jam ni's into function and loop
for ( int i = 1; i < 100; i++ ) {
// set element at location i+1 to f(x)= (fraction)*((x)^exponent + 2)
n[ i + 1 ] = fraction*(pow( ((n[ i ]) ), exponent ) + 2);
}
//header
cout << "Element" << setw( 13 ) << "Value" << endl;
// output each array element's value
for ( int j = 1; j < 100; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
return 0;
}
输出
Enter x_1
1
Element Value
1 1
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
....
我的预期输出在哪里
Element Value
1 1
2 0.42857142857
3 0.29695960016
4 0.2894553405
5 0.28917883433
6 0.28916891514
7 0.28916855966
。
背景:我正在尝试编写一个简单的程序,询问您的\$x_1\$是什么,并在给定一些级数函数计算器的情况下将\$x_1\$报告给\$x_{100}\$ - 就像一个序列计算器,其中\$x_{n+1} = f(x_n(\$。在这个例子中,我们的函数是 (1/7(*((x(^3 + 2(。
你们能提供一些资源来编写其他函数吗?我现在有 \$x_{n+1}=f(x_n(=(1/7(*((x_n^3(+2(\$。
每当我查找 c++ 数学函数时,我都会得到诸如如何使用绝对值函数或如何将我的 cpp 文件用作函数本身之类的东西,但没有收到有关编写此类数学函数的信息。
要向x_100报告x_1,您不需要 101 个元素的数组,而需要一个包含 100 个元素的数组,索引范围从 0 到 100 个独占。数组的索引比从顺序 1 开始的序列元素的顺序少 1。
可以使用值初始化在与声明相同的语句中将数组的所有元素设置为 0。
C++两个整数的除法结果是一个整数,这就是为什么你的fraction
数是0。因此,要获得一个非截断值,其中一个操作数应该是双精度数(另一个操作数将在除法之前由编译器提升为双精度(。
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
constexpr size_t elems_len = 100;
int main()
{
double n[elems_len]{}; // value initialization, all elements of n are set to 0
double exponent = 3;
// one of the operands should be double to avoid integer division and truncation
double fraction = 1.0 / 7;
cout << "Enter x_1" << endl;
cin >> n[0];
for (size_t i = 1; i < elems_len; i++) {
n[i] = fraction * (pow(n[i-1], exponent) + 2);
}
cout << "Element" << setw(13) << "Value" << endl;
cout << fixed << setprecision(11);
for (size_t i = 0; i < elems_len; i++) {
cout << setw(7) << i + 1 << setw(25) << n[i] << endl;
}
}
相关文章:
- 我关于函数"Assert"的C++代码有问题
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++类中的友元函数有问题?
- 虚拟 CTOR 的克隆函数实现是否有问题
- C++有问题的函数,数组到列表
- C++序列计算器x_{n+1} = f(x_n),数学函数有问题
- (c++)无法让 void 函数工作,主.cpp内部的几行也有问题
- 此函数是否对套接字有问题?
- 使用 std::weak_ptr 和别名构造函数中断循环引用:声音或有问题
- C++中的合并函数算法有问题
- 通过初始化列表调用另一个类的构造函数.有问题
- 我的哈希函数有问题吗?
- 我无法创建公共继承的构造函数有问题C++
- 函数和数组有问题
- Assert()函数抛出一个错误——操作符有问题
- 调用函数有问题
- 初学者对类和函数有问题
- Fprintf对函数返回的字符有问题
- c++的析构函数有问题
- 调用带指针的类函数有问题