반응형

C++ 기초 플러스 4판 7장  : 함수 _ 프로그래밍연습 9번

#include <iostream>
using namespace std;

double calculate(double, double, double (*pt)(double , double) );
double add(double, double);
double aver(double, double);
double subtraction(double x, double y);
double division(double x, double y);

int main()
{
 double num1, num2;
 double (*pt[3]) (double, double);  // double type 인자 2개 갖는 함수의 주소를 넣는 변수 배열
 pt[0] = add;  // 초기화
 pt[1] = aver;
 pt[2] = subtraction;

 double (*ps) (double, double) = division;

 cout << "input two number! \n";
 cout << "subtration and division excute from big number to small number\n";
 cout << "if invalid input, than exit\n";
 
 while( (cin >> num1) >> num2 ){ // 숫자가 아니면 실패 루프 종료
  cout << "addition : " << calculate(num1, num2, pt[0]) << "\n"; // 배열로 사용
  cout << "average : " << calculate(num1, num2, pt[1]) << "\n";
  cout << "subtraction : " << calculate(num1, num2, pt[2]) << "\n";
  cout << "division : " << calculate(num1, num2, ps) << "\n"; // 단독변수로 사용

  cout << "again? two input!\n";
 }

 cout << "fail! to exit! \n";

 return 0;
}


double add(double x, double y){
 return x + y;
}

double aver(double x, double y){
 return (x + y) / 2;
}

double subtraction(double x, double y){
 if(x > y) return x - y;
 else return y - x;
}

double division(double x, double y){
 if(x > y) return x / y;
 else return y / x;
 
}

double calculate(double num1, double num2, double (*pt)(double , double) ){
 return (*pt)(num1, num2);
}

반응형
Posted by Rainfly
l