C++ 表达式必须具有常量值,变量不能用作定义数组大小的常量

C++ 表达式必须具有常量值,变量不能用作定义数组大小的常量,c++,debugging,C++,Debugging,我试图生成这段代码,但在从双b[n];;开始的双精度函数中有和错误;。我得到的错误是,表达式必须有一个常量值,变量“n”不能用作常量。如果您能提供任何帮助,我们将不胜感激 //Get inputs from user double V = 0; // shear load applied int n; double H_total = 0; double A_total = 0; double a = 0; double I = 0; double t = 0; double e = 0

我试图生成这段代码,但在从双b[n];;开始的双精度函数中有和错误;。我得到的错误是,表达式必须有一个常量值,变量“n”不能用作常量。如果您能提供任何帮助,我们将不胜感激

//Get inputs from user

double V = 0;    // shear load applied
int n;
double H_total = 0;
double A_total = 0;
double a = 0;
double I = 0;
double t = 0;
double e = 0;
double y_bar = 0;

cout << "Input the shear load applied in [N]: " << endl;
cin >> V;

cout << "Input number of sections: " << endl;
cin >> n;

double b[n];
double h[n];
double A[n];
double y[n];
double Q[n];
double Tau[n];
for (int i = 1; i <= n; i++) { // Calculates variables to find shear stress

    cout << "Width of section " << i << " in [mm]: " << endl;
    cin >> b[i];

    cout << "Height of section " << i << " in [mm]: " << endl;
    cin >> h[i];

    H_total += h[i];
    A[i] = b[i] * h[i];
    A_total += A[i];
    y[i] = H_total - 0.5 * h[i];
    a += A[i] * y[i];
    y_bar = a / A_total;

}

cout << "Applied shear force, V = " << V / 1000 << " kN" << endl;
cout << "Y coordinate of the centroid for given cross section, Y_Bar = " << y_bar << " mm" << endl;

for (int i = 1; i <= n; i++) { // Finds moment of inertia

    double d = (y[i] - y_bar);

    I += (b[i] * pow(h[i], 3.0) / 12.0) + (A[i] * pow(d, 2.0));

}

cout << "Moment of Inertia, I = " << I << " mm^4" << endl;

for (int i = 1; i <= n; i++) { // Calculates first moment of inertia

    Q[i] = A[i] * (y[i] - y_bar);

}

for (int i = 1; i <= n - 1; i++) {

    if (b[i] <= b[i + 1]) {

        t = b[i];

    }
    else {

        t = b[i + 1];

    }

    Tau[i] = (abs(V * Q[i]) / (I * t));

}

for (int i = 1; i <= n - 1; i++) {

    if (i <= 2) {

        e += Tau[i];

    }
    else {

        e -= Tau[i];

    }
    cout << "Shear stress between sections " << i << " and " << i + 1 << " = " << e << " MPa" << 
endl;

}
}
首先是双b[n];不是函数,而是数组。此错误在二维阵列中很常见。但是,这里没有使用任何二维数组。此外,除非您提供导致此错误的特定输入,否则您的代码没有错误。 您可以看到一些随机输入的输出:

Applied shear force, V = 0.004 kN
Y coordinate of the centroid for given cross section, Y_Bar = 3.29661 mm
Moment of Inertia, I = 322.476 mm^4
Shear stress between sections 1 and 2 = 0.147082 MPa
Shear stress between sections 2 and 3 = 0.231598 MPa

可能重复的Make it std::vector bn;和其他数组类似。欢迎使用堆栈溢出。您的问题太模糊,代码太长。编写代码时,不要试图一次编写整个程序。从一个小而简单、工作完美的东西开始,然后一次增加一点复杂性,在每一步都进行测试,永远不要添加不起作用的代码。你的标题不是对问题的描述。未来有同样问题的程序员不会知道这描述了其他程序员所面临的问题。我修正了标题。那么我如何修正这个问题呢?正如我在回答中提到的,你的代码不会产生任何错误。尝试这些头文件,包括和。我有这两个头文件在那里,它仍然不工作。我知道手动输入变量的值是有效的,但我需要能够根据用户输入进行复制。我是否可以通过此设置使其正常工作?