Добавил:
Upload
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:05. Функции / Examples / 08_function_variables / 08_function_variables
.cpp#include <iostream>
using namespace std;
// func_t - тип функций, принимающих один параметр double
// и возвращающий значение типа double
typedef double (*func_t)(double);
double round(double a)
{
return (int)(a + 0.5);
}
double noaction(double a)
{
return a;
}
int main()
{
double x;
cout << "Enter X value: ";
cin >> x;
cout << "What function to apply:" << endl;
cout << "1. sin" << endl;
cout << "2. cos" << endl;
cout << "3. round" << endl;
int choice;
cin >> choice;
if (choice <= 0 || choice > 3)
choice = 0;
// Массив функций типа func_t
func_t functions[] = {noaction, sin, cos, round};
// double (*functions[])(double) = {noaction, sin, cos, round}; // другой способ
// Вызов функции из массива функций
double result = functions[choice](x);
cout << "function(x) = " << result << endl;
// Объявление с инициализацией переменной-функции типа func_t
func_t myFunc = sin;
// double (*myFunc)(double); // другой способ
return 0;
}