본문 바로가기

Developer/C

함수 예문

반응형

#include<stdio.h>
double calculation(double x,double y,int z)
{ if(z==1)
  return x+y;
 if(z==2)
  return x-y;
 if(z==3)
  return x/y;
 if(z==4)
  return x*y;}

int main(void)
{
 int z;
 double x,y;
 printf("두 수를 입력하시오");
 scanf("%lf",&x);
 scanf("%lf",&y);
 printf("연산자를 입력하시오(1+ 2- 3/ 4*)");
 scanf("%d",&z);
 printf("%f",calculation(x,y,z));

 return 0;
}

 

 

#include<stdio.h>
int fibonacci(int i)
{
 if(i<=2)
  return 1;
 else
  return fibonacci(i-2)+fibonacci(i-1);
}

int main(void)
{
 int f=1;
 while(f<=10)
  {printf("%d\n",fibonacci(f));
   f++;}
 return 0;
}

 

 

많이들 쓰이는 함수 예문이다. 위는 계산기, 밑은 피보나치이다.

int fibonacci(int i)

와 같이 피보나치라는 int형 i라는 변수를 사용하는 함수를 선언해주고, 그것을 main에서 활용하는 것이다.

여러번 쓰거나 main이 너무 길떄 유용하다.

반응형

'Developer > C' 카테고리의 다른 글

스위치 예문  (0) 2012.07.13
비트연산자 예제  (0) 2012.07.13
array 예제  (0) 2012.07.13
if문과 그 예제  (0) 2012.07.13
ASCII코드란? (+예제)  (0) 2012.07.13