数组下标的类型"float*[float]"无效

invalid type 'float*[float]' for array subscript

本文关键字:float 无效 下标 类型 数组      更新时间:2023-10-16

我想显示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";
}

你试图解决的问题实际上并不是你需要解决的问题。此代码中有很多错误,可以简单地删除,因为您使用了错误的工具。

这里不需要数组。如果你这样做了,你需要分配一个,而不是传入空的东西,否则你会越界使用它。对于这样的数组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[]={};不是以后可以添加到的空数组,它是一个永久零长度的数组,或者换句话说,它是无用的。
  • 密切注意您定义的变量,避免在同一范围内定义它们两次。
  • 学习时打开所有编译器警告,以收到潜在问题的警报。C++充满了细微差别和陷阱。