-
혼자 공부하는 C언어_Chapter.2 정리C 2020. 7. 29. 21:15반응형
| 함수
함수는 일정한 기능을 수행하는 코드 단위를 의미한다. main 함수는 프로그램의 시작을 의미하므로 반드시 있어야 한다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersint main(void) //머리 { 10 + 20; return 0;//프로그램 종료 } 1행 : 함수의 머리 부분이다. 함수 원형이라고도 한다. 함수의 이름과 필요한 데이터를 표시한다.
2~5행 : 함수의 몸통 부분이다.
함수를 작성할 때는 일정한 간격으로 들여쓰는 것이 가독성이 있다. 기본 들여쓰기는 4칸이다.
#include <stdio.h> : stdio.h는 standard input output을 의마하며 C 언어에서 기본으로 사용하는 입출력 함수가
들어 있다.
| 출력 함수
printf는 stdio.h에 포함되어 있는 출력 함수이다. printf 함수로 출력할 때는 제어문자를 사용한다.
1) \n(개행, new line) : 다음 줄로 이동한다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#include <stdio.h> int main(void) { printf("Be happy\n"); printf("My friend\n"); } 실행 결과 :
Be happy My friend
2) \t (탭.tab) : 다음 탭 위치로 이동
#include <stdio.h> int main(void) { printf("Be happy\t"); printf("My friend"); return 0; }
실행 결과 :
Be happy My friend
3) \b(백스페이스, backspace): 한 칸 왼쪽으로 이동
#include <stdio.h> int main(void) { printf("Nicy\be\tday\n"); return 0; }
실행 결과 :
Nice day
제어 문자에 위해 Nicy의 y 위에 e가 덧 쓰여진 결과가 출력되었다.
4) \r(캐리지 리턴, carriage return): 맨 앞으로 이동
#include <stdio.h> int main(void) { printf("Hat\rM\n"); return 0; }
실행 결과 :
Mat
5) \a(알럿 경보, alert):벨소리
제어문자 \aㅜ에 의해 벨소리를 낸다.
#include <stdio.h> int main(void) { printf("Hat\rM\a\n"); return 0; }
실행 결과 : 안타깝게도 소리를 담을 순 없으니 삐이익 ---?
| 정수와 실수 출력
printf는 기본적으로 문자열을 출력하는 함수이기 때문에 숫자를 출력할 때는 변환 문자를 사용해서 문자열로 변환하는 과정이 필요하다.
1) %d : 정수 출력
#include <stdio.h> int main(void) { printf("%d\n",10); return 0; }
실행 결과 :
10
2) %lf : 실수 출력
#include <stdio.h> int main(void) { printf("%lf\n",3.14); return 0; }
실행 결과 :
3.140000
3) 소수점 자릿수 지정과 반올림
%lf로 실수를 출력하면 소수점 이하 6자리까지 출력된다.
이때, 위처럼 몇 자리까지 출력할지 지정해 줄 수 있다.
잘리는 값은 반올림하여 출력된다.
3.1
4) 변환 문자 여러 개 사용하기
#include <stdio.h> int main(void) { printf("%d과 %d의 합은 %d입니다.\n",10,20,10+20); return 0; }
실행 결과 :
10과 20의 합은 30입니다.
728x90'C' 카테고리의 다른 글
혼자 공부하는 C언어_ Chapter.1 정리 (0) 2020.07.29