c++ - 表达式必须有常量值,变量不能用作定义数组大小的常量
问题描述
我正在尝试生成此代码,但在double
从double 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;
}
}
解决方案
首先double 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
推荐阅读
- python - Django嵌套重组
- java - android.app.ActivityManager.AppTask 访问静态类的非静态方法
- r - 上传文件并在闪亮中使用summarytools
- arrays - 如何使用 Laravel 将 JSON 元素保存为数据库中的记录?
- reactjs - 无法读取未定义 npm ERR 的属性“拆分”!代码生命周期
- c# - 按下 Enter 键时,具有 Janus Gridex 的 WinForm 挂起/冻结
- node.js - 配置 PollyJS 以忽略某些请求
- c# - C# 中的冗余存储或 linq 语句?
- html - how to change the font size of the text on my button (HTML/CSS)
- unix - Groovy:如何获取某个日期的 unix 时间而不是当前日期?