|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
3、(基础题)函数指针的应用:sin(x)、cos(x)、tan(x)都是三角函数,形参、函数返回结果都是double类型,它们的声明、定义已包含在math.h中。请编写编程实现如下功能:根据输入的整数(1、2、3)分别调用sin(x)、cos(x)、tan(x),x的值也需要输入,请补充程序所缺代码:
#include <stdio.h>
#include <math.h>
int main()
{
int n;
double x;
printf("请输入整数1,2,3(分别调用sin(x)、cos(x)、tan(x)):");
scanf("%d",&n);
printf("请输入x的值:");
scanf("%lf",&x);
(1) //定义指向函数的指针变量;
void fun(double (*p)(double z),double x, int n) ;//函数声明
(2) //调用fun()函数
return 0;
}
//函数功能: 根据n的值(1,2,3)分别调用sin(x)、cos(x)、tan(x),并输出结果;n为其它值时,提示“输入的数据有误,不能调用任何函数!”
void fun(double (*p)(double z),double x, int n)
{
//函数的实现代码
}
我测试没有问题,如果真的不行,就不要这样写了,一行一行打印吧: - #include <stdio.h>
- #include <math.h>
- int main()
- {
- int n;
- double x;
- printf("请输入整数1,2,3(分别调用sin(x)、cos(x)、tan(x)):");
- scanf("%d", &n);
- printf("请输入x的值:");
- scanf("%lf", &x);
- double(*p)(double) = NULL;//定义指向函数的指针变量;
- void fun(double (*p)(double z), double x, int n);//函数声明
- fun(p, x, n); //调用fun()函数
- return 0;
- }
- //函数功能: 根据n的值(1,2,3)分别调用sin(x)、cos(x)、tan(x),并输出结果;n为其它值时,提示“输入的数据有误,不能调用任何函数!”
- void fun(double (*p)(double z), double x, int n)
- {
- double y;
- if (n == 1)
- {
- p = sin;
- y = (*p)(x);
- printf("sin(%.2f)=%f\n\n", x, y);
- }
- else if (n == 2)
- {
- p = cos;
- y = (*p)(x);
- printf("cos(%.2f)=%f\n\n", x, y);
- }
- else if (n == 3)
- {
- p = tan;
- y = (*p)(x);
- printf("tan(%.2f)=%f\n\n", x, y);
- }
- if ((n == 1) || (n == 2) || (n == 3))
- {
- ;
- }
- else
- printf("输入数据有误,不能调用任何函数!\n");
- }
复制代码
|
|