函数指针疑惑
我看了一个函数指针的程序,有个疑惑,不用看程序,可以先看我的问题,毕竟我的问题和程序没多大关系
#include <stdio.h>
#define F 4
float add(float x, float y);
float subtract(float x, float y);
float multiply(float x, float y);
float divide(float x, float y);
int main(void)
{
char command[5];
float x, y;
float (*p[F])(float x, float y) = {add, subtract, multiply, divide};
while(1)
{
printf("Select function:\n");
printf("1 : x + y\n");
printf("2 : x - y\n");
printf("3 : x * y\n");
printf("4 : x / y\n");
printf("q : quit\n");
gets(command);
if ( command[0] < '1' || command[0] > '4' ) break;
printf("input x, y:");
scanf("%f%f", &x, &y);
getchar();
printf("result is : %g\n", (*p[ command[0] - '1' ]) (x,y) );
}
return 0;
}
float add(float x, float y)
{
return x + y ;
}
float subtract(float x, float y)
{
return x - y ;
}
float multiply(float x, float y)
{
return x * y ;
}
float divide(float x, float y)
{
return x / y ;
}
疑惑在这:
(*p[ command[0] - '1' ]) (x,y)
如果我输入了‘1’,那么这句话就变成(*p['1'])(x,y),我想这个‘1’是字符的‘1’,而不是(*p[1])(x,y)
所以,我想问的问题,你们懂的,请回答我
[解决办法]
我猜,如果你输入 1,'1' = 49 ,1-49 = -48,那么 应为为 *p[-48]啊。
我感觉LZ问的这个 ?
[解决办法]
你输入1 '1'-'1'=0 那么应该是(*p[0])(x,y) you think?