C++调用calcbmi报错:无法将float*转float、数组下标类型错误如何解决
问题排查与解决
错误根因
两类报错均来自calcbmi函数的形参定义错误:
- 当前
calcbmi的前三个参数定义为单个float类型变量,但调用时传入的是weight/height/bmi三个数组的数组名(本质是float类型指针),因此触发「cannot convert 'float*' to 'float'」的传参类型不匹配错误。 - 单个
float变量不支持使用[下标]的方式访问元素,因此函数内部循环访问weight[i]/height[i]/bmi[i]时触发「Invalid types float[int] for array subscript」错误。
额外说明:你代码中float weight[size]这类写法属于变长数组(VLA),是C语言特性,标准C不提供官方支持,仅部分编译器做了扩展兼容,如果需要编写标准C代码,建议替换为std::vector或者动态申请内存。
修复方案
仅需要修改calcbmi函数的形参定义,将前三个参数改为数组类型即可,修改后的函数头为:
void calcbmi (float weight[], float height[], float bmi[], int size)
修改后的完整可运行代码如下:
#include <iostream> #include <cmath> using namespace std; void inputweight(float weight[], int size) { cout << "Enter weights in kilogram: "; int i = 0, w; while (i < size) { cin >> w; if (w >= 45 && w <= 200) { weight[i] = w; i++; } else{ cout << "The value should be between 45-200." << endl; } } cout << "Weights: "; for (int i = 0; i < size; i++) { cout << weight[i] << " "; } cout << endl; } void inputheight(float height[], int size) { float h; cout << "Enter height in cm: "; for (int i = 0; i < size; ) { cin >> h; if (h >= 140 && h <= 200) { height[i] = h; i++; } } cout << "Heights: "; for (int i = 0; i < size; i++) { cout << height[i] << " "; } cout << endl; } // 仅修改了该行的形参类型 void calcbmi (float weight[], float height[], float bmi[], int size) { for (int i = 0; i < size; i++) { bmi[i] = weight[i] / (height[i] / 100 * height[i] / 100); } cout << "BMI values:" << endl; for (int i = 0; i < size; i++) { cout << bmi[i] << " " << endl; } } int main() { int size; cout << "Enter number of students: "; cin >> size; // 变长数组写法仅兼容支持C++ VLA扩展的编译器 float weight[size], height[size], bmi[size]; inputweight(weight, size); inputheight(height, size); calcbmi(weight, height, bmi, size); return 0; }
内容的提问来源于stack exchange,提问作者Rithik Zoysa
相关产品推荐
相关产品推荐

