问题:
解答:
cpp
#include <iostream>
using namespace std;
double add(double a, double b)
{
return a + b;
}
double mul(double a, double b)
{
return a * b;
}
double sub(double a, double b)
{
return a - b;
}
double div(double a, double b)
{
return a / b;
}
double calculate(double num1, double num2, double (*p)(double, double))
{
return p(num1, num2);
}
int main()
{
double num1 = 0.0;
double num2 = 0.0;
double res = 0.0;
cout << "请输入第1个数值:";
cin >> num1;
cout << "请输入第2个数值:";
cin >> num2;
res = calculate(num1, num2, add);
cout << num1 << "+" << num2 << "=" << res << endl;
res = calculate(num1, num2, mul);
cout << num1 << "*" << num2 << "=" << res << endl;
double (*p[4])(double, double);
double result[4];
p[0] = &add;
p[1] = &mul;
p[2] = ⊂
p[3] = ÷
for (int i = 0; i < 4; i++)
{
result[i] = calculate(num1, num2, p[i]);
}
cout << endl;
cout << num1 << "+" << num2 << "=" << result[0]<< endl;
cout << num1 << "-" << num2 << "=" << result[2] << endl;
cout << num1 << "*" << num2 << "=" << result[1] << endl;
cout << num1 << "/" << num2 << "=" << result[3] << endl;
return 0;
}
运行结果:
考查点:
- 函数指针
- 指针数组
注意:
-
函数指针的定义
-
函数指针数组定义
-
函数指针的指向
2024年8月31日21:03:20