编写一个程序,用指向函数的指针数组执行菜单。例如,在菜单中选择a会激活由数组第一个元素指向的函数。
#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 ; }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题