C++ c++;序列计算器x{n+;1}=f(x#n),数学函数有问题
代码示例C++ c++;序列计算器x{n+;1}=f(x#n),数学函数有问题,c++,C++,代码示例 #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 fra
#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;
}
我的预期输出将在哪里
Element Value
1 1
2 0.42857142857
3 0.29695960016
4 0.2894553405
5 0.28917883433
6 0.28916891514
7 0.28916855966
背景:我正试图编写一个简单的程序,询问你的\$x\u 1\$是什么,并报告\$x\u 1\$到\$x\u{100}\$,给定一些系列函数计算器——比如序列计算器,其中\$x\u{n+1}=f(x\u n)\$。在本例中,我们的函数是(1/7)*((x)^3+2)
你们能为编写其他函数提供一些资源吗?我现在有\$x{n+1}=f(x{n)=(1/7)*((x{n^3)+2)\$
当我查阅C++数学函数时,我会得到一些东西,比如如何使用绝对值函数,或者如何将我的CPP文件作为函数本身,而不是编写这样的数学函数的信息。p> 要将x_1报告给x_100,您不需要101个元素的数组,而需要100个元素的数组,索引范围从0到100。数组的索引比从顺序1开始的序列元素的顺序少一个 可以使用值初始化在声明之外的同一语句中将数组的所有元素设置为0 在C++中,两个整数的除法结果是一个整数,这就是为什么你的<代码>分数>代码>编号为0的原因。因此,要获得一个非截断值,其中一个操作数应该是double(另一个操作数将在除法之前由编译器提升为double)
#包括
#包括
#包括
使用名称空间std;
constexpr size\u t elems\u len=100;
int main()
{
双n[elems_len]{};//值初始化,n的所有元素都设置为0
双指数=3;
//其中一个操作数应为双精度,以避免整数除法和截断
双分数=1.0/7;
coutn[0];
对于(大小i=1;i 我能不能不再读你的问题了“程序运行了,但仍然给我一些奇怪的错误。”。您能否澄清或删除这一点,因为出错和工作通常是相互排斥的。这需要输入。的输入、实际输出和预期输出是什么?您不能在代码中设置它们,而不是让我键入它们,因为我们只处理修复问题?嗯,编译器有一点。n[i+1]可以位于数组之外。看起来您对是否要跳过第一个或最后一个感到困惑。需要注意的是,像7这样的数字文字被假定为整数。这就构成了1/7整数数学。不允许使用分数。1/7=0。1.0/7强制浮点数学,因此您将得到更符合预期的答案s、 正如@user4581301所说的1/7=0,因为它被解释为整数除法`
Element Value
1 1
2 0.42857142857
3 0.29695960016
4 0.2894553405
5 0.28917883433
6 0.28916891514
7 0.28916855966
#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;
}
}