代码示例
#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;
}
}