1 / 49

제 21 강

제 21 강. 함수의 기초. “function” 의 두가지 뜻. 수학의 함수 기능. 우리가 아는 함수. c = getchar(); putchar(c); printf(... ); n = scanf( ... );. 함수란 ?. 오공아 , 아이스크림 좀 사오면 안되겠니 ~. Ogong(" 아이스크림 ");. 이름 부르기. 원하는 구체적 내용. 함수는. 정해진 범위의 일을 한다 .

manasa
Télécharger la présentation

제 21 강

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 제 21 강 함수의 기초 shcho.pe.kr

  2. “function” 의 두가지 뜻 • 수학의 함수 • 기능

  3. 우리가 아는 함수 • c = getchar(); • putchar(c); • printf(... ); • n = scanf( ... );

  4. 함수란 ? 오공아, 아이스크림 좀 사오면 안되겠니~ Ogong("아이스크림"); 이름 부르기 원하는 구체적 내용

  5. 함수는... • 정해진 범위의 일을 한다. • getchar()가 하는 일은 오직 1가지printf()가 하는 일은 좀더 변화는 있지만 근본적으로 "출력" • 형식이 정해져 있다. • 함수의 이름, 괄호 안에 넣어 주어야 할 무엇... • 무언가 일을 하고 결과를 전달해주기도 한다.c = getchar(); • 무언가 일을 하고 그냥 끝내기도 한다.putchar(c); • 누군가 미리 만들어 놓지 않았으면 쓸 수가 없을 것이다.

  6. C functions • similar to mathematical functions • f(x1,x2,...xn)과 같이 “호출” • 결과를(있으면) 임시 메모리에 저장. • 예: • putchar('a'); • getchar(); • c = getchar(); • y = sin(0.3);

  7. C functiony = sin(x); x 값이 필요 실행적 의미(x 값 줄께, y 값 다오) sin(x) = y; 불가능 Math function x 값은 나중에 대입 선언적 의미 도 같다 C functions and Math functions

  8. 다음 shcho.pe.kr

  9. lab21_01/tri.c • 삼각함수를 호출해서 써본다. 다음과 같은 형식으로 0도에서 90도까지 5도 간격으로 sin, cos, tan의 값을 출력한다. 모든 수는 double 타입으로 선언. 출력은 소수이하 둘째 자리 까지만. • for 문을 이용한다. 20강의 마지막 부분 주의사항을 참조. • 삼각 함수는 각도가 아닌 호도(radian)으로 계산 하므로 각도에서 호도로 변경해 주어야 한다. x가 각도라면 호도 r 은 r = x * 3.14 / 180으로 계산한다. • #include <math.h> • 컴파일 시는 gcc tri.c –lm으로 컴파일해야 한다. • 예: (탭을 이용하여 줄을 바르게 맞출 것) • 각도 호도 sin cos tan • 0 0.00 0.00 1.00 0.00 • 5 ... • ...

  10. 언제 사용하나? • 같거나 유사한 일의 반복 • 자주 쓰이는 복잡한 수학 계산 (예: sin, cos) • 큰 일을 나누어 여러 사람이 협동 작업 • 의미 있는 덩어리의 일을 함수로 대치함으로써 프로그램의 이해를 돕는다. • 대개의 프로그램에서 cos(x)+sin(x)라고만 쓰면 알아 듣는다. 실지로 cos(x)를 계산하는 프로그램을 다 써놓을 필요가 없다. “I don’t want to know!”

  11. Parameters(인자, 인수) • printf(“%d\n”, x); • putchar('a'); // parameter 하나. • c = getchar(); // parameter가 없다. 함수 이름 둘째 인자 첫째 인자 콤마로 구분

  12. 이미 정의된 함수의 사용 • printf(“%d\n”, x); // 반환 값을 사용하지// 않는 경우 • c = getchar(); // 반환 값을 사용하는 경우

  13. 함수 호출과 수식 • c = a + b; a + b 의 결과는 임시로 저장 저장된 결과가 c에 copy됨. • c = getchar(); getchar()의 결과가 임시로 저장 저장된 결과가 c에 copy됨. "반환 값", "리턴값", "함수호출식의 값" = 다 같은 뜻

  14. Type • 함수의 return 값에는 타입이 정해져 있다. • i = getchar(); // int • f = sin(0.5 * 3.14 / 180); // double

  15. r-value only(remember?) • y = f(x) + 3.5; // OK • f(x) = 3.5 ; // Not allowed • max(x)++ ; // Not allowed

  16. 다음 shcho.pe.kr

  17. 함수의 정의 방법 • typefunction_name(argument_list){ • 실제 할 일; • } • 예: • int add(int x, int y){ • // anything goes in here • return x+y; • } 이 값이 호출식의 값이 됨

  18. int add(..){ } int main(..){ .. add(..);} int main(..){ .. add(..);} int add(..){ } 함수의 위치 O X

  19. int add(..){ ...} int main(..){ ...} 어쩐지 비슷하네?

  20. Return value (반환 값) • int add(int x, int y){ • return x+ y; • } • … • main(){ • … • i = add(3,5)

  21. 실습 lab21_02/simple.c;square.c • 1. simple.c • 목적: 간단한 정수 함수의 작성 연습 • 다음의 내용을 입력하여 실행하여보라. • int simple(){ • return 1; // So simple! • } • int main(){ • int i; • i = simple(); • printf("%d\n", i); • }

  22. 실습 lab21_02/계속 • 2. square.c • 내용: 하나의 정수를 인자로 받아 받은 수의 제곱 값을 돌려주는 함수의 작성 및 이용 • return type은 int • 함수 이름은 square • parameter는 int x를 사용 • main 함수에서는 y = square(3);을 호출하여 y값을 출력해 보고 다시 square(5)도 출력해 본다.

  23. Local variables & parameters • 함수 안에서만 사용할 변수가 있다면 함수 안에서 선언한다. • int sumto(int n){ • int i, sum; // 이 변수는 함수 안에서만 사용. • for (i=0; .. ; ..){ • ... • } • return sum; • }

  24. lab21_03/funvar.c • 1에서 n까지 더해서 결과를 돌려주는 함수 int add_to_n(int n);을 정의하고 • add_to_n(10) 값을 출력해보라. • 1부터 n까지 세기 위한 변수 i와 합을 구하기 위한 변수 sum을 add_to_n 함수의 지역 변수로 선언해서 사용할 것.

  25. void type • void prt(int x){ • printf(“x value is: %d\n”, x); • return; • } prt(int x){ ... } No return value x = prt(3) + 1; X prt(3); O

  26. Implicit return • void print_int(int x){ • printf(“x value is: %d\n”, x); • } • int print_int(int x){ • printf(“x value is: %d\n”, x); • // what’s missing ? • }

  27. Can return anytime • int divide(int x, int y){ • int result; • if (y==0) return -1; • result = x / y; • return result; • }

  28. 다음 shcho.pe.kr

  29. 실습 lab21_04/getput.c • Parameter로 주어진 int를 줄바꿈 기호와 함께 인쇄하는 함수 void put_int(int x)와 정수 하나를 scan 해서 돌려주는 int get_int()를 작성해서 • main 함수 안에서는 정수 변수 y에 정수를 읽어들인다. 그런데 scanf를 직접 쓰지 않고 y = get_int()를 사용한다. 출력 역시 printf를 쓰지 않고 put_int를 사용한다. • get_int 함수는 읽기에 실패하면 INT_MIN을 돌려준다. (#include <limits.h> 필요) • int main(){ • int y; • while ((y=get_int()) != INT_MIN) put_int(y); • }

  30. Parameters • formal parameters(형식 인자) and actual parameters(실질 인자) • int add(int x, int y){ • return x+ y; • } • … • main(){ • int a,b; • i = add(a,b);

  31. Not names, but order • int subtract(int x, int y){ • return x - y; • } • … • main(){ • int x=1, y=2; • i = subtract(y,x); // i의 값은?

  32. Parameter type matching • int add(int x, int y){ • return x+ y; • } • … • int main(){ • double b; • int i,j; • i = add(3.5, b); • j = add(1, i); • }

  33. Number of Parameters • int add(int x, int y){ • return x+ y; • } • … • int main(){ • int i,j; • i = add(3); • j = add(3,4,5); • }

  34. Return types must match • int add(int x, int y){ • return x+ y; • } • int half(int x){ • return 0.5 * x; • }

  35. Types • int max(int x, int y){ • if (x>y) return x; • else return y; • } • … • main(){ • int i; • i = max(3,5); • …

  36. 다음 shcho.pe.kr

  37. Define it before you use it • float fmin(float x, float y){...} • int main(){ • z1 = fmin(x,y); • z2 = fmax(x,y); • } • float fmax(float x, float y){...}

  38. A prototype will do • a forward declaration • float fmin(float x, float y); • main(){ • z1 = fmin(x,y); • } • float fmin(float x, float y){ • if (x>y) return x; else return y; • }

  39. 실습 lab21_05/ffun.c • 목적: float 함수 작성법 연습 • 내용: 두 실수 x,y를 인자로 받아서 x2+2xy+y2을 계산하여 돌려주는 함수 square()를 작성하라. • 제곱의 계산은 같은 수끼리 곱하면 된다. • test: main 함수에서 square(2.5, 3.5)와 square(1.5, 3.5)의 값을 print하라.

  40. Example: Anything wrong? • float square(float x, float y){ int z; z = x*x + 2*x*y + y*y; • return z; • }

  41. 실습 lab21_06/proto.c • 목적: prototype 선언 • 내용: 정수 n을 인자로 받아서 1부터 n까지의 합을 계산하여 돌려주는 함수를 작성하고 이름을 add_to_n이라고 하자. • 프로토타입은 int add_to_n(int n);과 같이 main 함수 이전에 선언한다. 실제 함수의 정의는 main 함수의 뒤에 놓는다. • add_to_n(5)를 인쇄하라, 또 add_to_n(10)을 인쇄하라. • hint: for 문을 사용하라.

  42. 실습 lab21_07/proto2.c 21_07.txt • 목적: prototype 선언 생략의 문제점 확인 • double dmax(double x, double y)는 두 수 중 큰 수를 돌려주는 함수이다. • 이 함수의 정의를 main 함수의 뒤에서 한다. • main함수의 앞에는 프로토타입만을 선언한다. • main 함수 내에서는 double x = dmax(1.5, 2.5);하고 x 값을 출력(%lf) 해 본다. • 이번에는 프로토타입을 지우고 (comment-out 하고서) 테스트해보라. 컴파일 때와 실행 때에 이전 버전과 어떠한 차이가 있는지 21_07.txt에 적어보라.

  43. 해설 • double dmax(double x, double y); • double x = dmax(1.5, 2.5); • double dmax(double x, double y){ • ... • }

  44. 실습 lab21_08/param.c • 목적: parameter 값의 변화 관찰 • void 타입의 함수 add_one(int x)를 작성하라. 함수 add_one은 인자로 받은 값(x)을 1 증가 시키는 함수이다. void 타입의 함수에서는 return 값이 없다. • 함수 내부에서 증가시키기 전의 x 값을 출력하고 증가시킨 후의 x 값을 또한 출력한다. • main함수에서는 i 값을 99로 하고 add_one(i)를 호출하되 호출 전 i 값을 출력하고 호출 후의 i 값을 다시 출력한다. • 출력된 4개의 값을 비교해 본다. 네 개의 출력 값이 각각 소스 코드의 어느 부분에서 출력을 한 것인지 출력된 순서대로 서술하라. (comment로)

  45. Code • #include <stdio.h> • int main(){ • i = 99; • print i; • add_one(i); • print i; • } • void add_one(int x){ • x 출력 • x++; • x 출력; • }

  46. “Call by value” • 실질 인자와 형식 인자 void add_one(int x){ ... } int main(){ ... // i = 99; add_one(i); ... } • 실질 인자의 값을 형식 인자에 복사 후 함수를 수행

  47. 수행 순서 add_one 함수 add_one 함수 add_one 함수 n 99 100 100 종료 +1 복사 main 함수 i main 함수 main 함수 main 함수 99 99 99 99

  48. Summary • 정의: type name(arg list){ body } • 사용: name(actual param); • r-value only • parameters must match • definition before use; or use prototypes • you cannot modify actual parameters in the function (call by value)

  49. 제 21 강 끝. 함수 shcho.pe.kr

More Related