首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数组下标的类型'float*[float]‘无效

数组下标的类型'float*[float]‘无效
EN

Stack Overflow用户
提问于 2020-06-30 16:22:23
回答 1查看 67关注 0票数 2

我想要显示x和f(x)的范围并将f(x)保存在数组中,但我总是得到这个错误:

代码语言:javascript
复制
invalid type 'float*[float]' for array subscript

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

代码如下:

代码语言:javascript
复制
#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";

}
EN

回答 1

Stack Overflow用户

发布于 2020-06-30 16:33:47

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

这里不需要数组。如果你这样做了,你需要分配一个,而不是传递一些空的东西,否则你就会越界使用它。对于这样的数组,在C++中使用std::vector

话虽如此,以下是代码的简化版本:

代码语言:javascript
复制
#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++充满了细微差别和陷阱。
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62653166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档