【发布时间】:2019-08-27 17:03:40
【问题描述】:
无法通过函数指针访问函数。
我正在编写一个基于美国和欧盟标准输入(身体质量指数计算器)的程序。 我的观点是使用一个函数“calcMethod”来计算 BMIndex,但尝试将其他函数的指针分配给这个函数会导致错误“调用的对象不是函数或函数指针”。任何帮助表示赞赏。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
float calcEU(float inputMass, float inputHeight)
{
float BMIndexF;
BMIndexF = inputMass / (inputHeight * inputHeight);
return BMIndexF;
}
float calcUS(float inputMass, float inputHeight)
{
float BMIndexF;
BMIndexF = 703 * inputMass / (inputHeight * inputHeight);
return BMIndexF;
}
int main()
{
float BMIndex , inputMass , inputHeight;
float heightColumn, massRow;
float *calcMethod ;
int Mod = 0;
int countRow , countColumn;
char unitStandard[2] , metricUnitH[2] , metricUnitM[2];
printf("Your measure units? EU (kg, m) or US (lb, in) \n");
gets(unitStandard);
if(strcmp(unitStandard, "EU") == 0)
{
Mod = 1;
strcpy(metricUnitH, "me");
strcpy(metricUnitM, "kg");
float (*calcMethod)(float , float) = &calcEU;
}
else if (strcmp(unitStandard, "US") == 0)
{
Mod = -1;
strcpy(metricUnitH, "in");
strcpy(metricUnitM, "lb");
float (*calcMethod)(float , float) = &calcUS;
}
else
{
printf("Wrong Input");
exit(-1);
}
printf("Introduce your body mass:\n");
scanf("%f", &inputMass);
printf("Introduce your height:\n");
scanf("%f", &inputHeight);
printf("\n");
for(countRow = 0; countRow <= 5; countRow++)
{
for(countColumn = 0; countColumn <= 5; countColumn++)
{
heightColumn = inputHeight - 0.1 * (3 - countRow);
massRow = inputMass - 1 * (3 - countColumn);
if(countRow == 0 && countColumn == 0) printf("H / M|");
if(countRow == 0 && countColumn != 0) printf("%.0f%s |", massRow , metricUnitM);
if(countColumn == 0 && countRow != 0) printf("%.1f%s |", heightColumn , metricUnitH);
if(countRow != 0 && countColumn !=0)
{
//this line causes error
BMIndex = (*calcMethod)(massRow , heightColumn);
printf("%.2f |", BMIndex);
}
}
printf("\n");
}
return 0;
}
注释行导致错误:被调用对象不是函数或函数指针
预计它不会引发错误并按预期工作。
【问题讨论】:
-
欢迎来到 Stack Overflow。请edit您的问题包含整个错误消息。还要指出是哪一行导致了错误。
-
最后,制作您的代码示例,以便我们可以编译它并得到相同的错误。特别是,添加
main()和所有必要的变量声明。 -
float (*calcMethod)(float , float) = &calcEU; }变量在}之后停止存在。 -
您在两个不同的
if块内声明和初始化两个不同的calcMethod变量。当您在显示的代码中调用它时,这两个声明都不在范围内。如果您声明一个calcMethod变量(在第一个if语句之上)并在每个if语句中分配给设计值,那么它应该可以工作。 -
与您的主要问题无关,但是:如果您想要来自用户的 2 个字母的响应,请不要声明一个大小为 2 的数组来保存它,甚至更多重要的是,永远不要使用
gets()阅读它! (1) 保存长度为 2 的字符串所需的大小是 3。 (2) 使用刚好大到足以容纳预期字符串的数组容易出错且毫无意义,因为它不会阻止用户尝试键入更长的东西。 (3)gets函数具有病态危险,已从 C 语言标准中删除,不应使用。
标签: c function function-pointers