我想要显示x和f(x)的范围并将f(x)保存在数组中,但我总是得到这个错误:
invalid type 'float*[float]' for array subscript有人能帮我吗?我还是卡住了。
代码如下:
#include <iostream>
#include <cmath>
#include <math.h>
using std::cin;
using std::cout;
using namespace std;
void displayValue(float funx[], float j, float x);
int main()
{
float num9[]={};
float a, r;
displayValue(num9, a, r);
return 0;
}
void displayValue(float funx[], float j, float x)
{
float i;
cout << "Please enter range of x: " << endl;
for (i=0; i<1; i++)
{
cin >> x >> j;
}
for (float i=1; i<=160.5; i++)
{
x+=0.5;
funx[i]=1/sin(x)+1/tan(x);
//1.2 Display f(x) and x within the range
}cout << x << " = " << funx[i] << "\n";
}发布于 2020-06-30 16:33:47
你试图解决的问题实际上并不是你需要解决的问题。这段代码中有很多错误,可以简单地删除,因为您使用了错误的工具。
这里不需要数组。如果你这样做了,你需要分配一个,而不是传递一些空的东西,否则你就会越界使用它。对于这样的数组,在C++中使用std::vector。
话虽如此,以下是代码的简化版本:
#include <iostream>
#include <cmath>
#include <math.h>
// Don't add "using namespace std", that separation exists for a reason.
// Separate the math function to make it clear what's being done
float f(const float x) {
return 1/sin(x)+1/tan(x);
}
// Define your functions before they're used to avoid having to declare
// then later define them.
void displayValue(const float min, const float max, const float step = 0.5)
{
for (float x = min; x <= max; x += step)
{
// Note how the f(x) function here is a lot easier to follow
std::cout << "f(" << x << ") = " << f(x) << std::endl;
}
}
int main()
{
std::cout << "Please enter range of x: " << std::endl;
// Capture the range values once and once only
float min, max;
std::cin >> min >> max;
// Display over the range of values
displayValue(min, max);
return 0;
}这里有一些重要的C++基础知识:
float num9[]={};不是一个可以在以后添加的空数组,它是一个永久长度为零的数组,或者换句话说,它是无用的。https://stackoverflow.com/questions/62653166
复制相似问题