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

Dan*_*nia 2 c++ c++11

我想显示 x 和 f(x) 的范围并将 f(x) 保留在数组中,但我总是收到此错误:

invalid type 'float*[float]' for array subscript
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗?我还是卡住了。

这是代码:

#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";

}
Run Code Online (Sandbox Code Playgroud)

tad*_*man 5

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

这里不需要数组。如果你这样做了,你需要分配一个,而不是传入空的东西,否则你会越界使用它。在 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;
}
Run Code Online (Sandbox Code Playgroud)

这里有一些重要的 C++ 基础知识:

  • float num9[]={};不是您以后可以添加到的空数组,它是一个永久零长度数组,或者换句话说,它是无用的。
  • 请密切注意您定义的变量,并避免在同一范围内将它们定义两次。
  • 在您学习警惕潜在问题的同时打开所有编译器警告。C++ 充满了细微差别和陷阱。

  • 我删除了我的答案以支持你的答案,但恕我直言,你应该添加一个关于“float”循环计数器的词。如果存在舍入误差,循环可能会比预期早/晚停止一次迭代 (2认同)