1 / 54

11 장 표준 라이브러리 (Standard Library)

11 장 표준 라이브러리 (Standard Library). 11 장 내용. 11-1 문자 처리 함수 11-2 문자열 처리 함수 11-3 기억장치 관리 함수 11-4 자료 변환 처리 함수 11-5 기타 함수. 표준 라이브러리 역할 및 종류. 표준 라이브러리 역할 프로그래머에게 편리하게 사용할 수 있는 다양한 종류의 함수를 제공 표준 라이브러리 종류 입출력함수 , 문자 및 문자열 함수 , 수치함수 , 시스템 함수 연관된 표준 헤더 파일

kalyca
Download Presentation

11 장 표준 라이브러리 (Standard Library)

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. 11장 표준 라이브러리 (Standard Library)

  2. 11장 내용 • 11-1 문자 처리 함수 • 11-2 문자열 처리 함수 • 11-3 기억장치 관리 함수 • 11-4 자료 변환 처리 함수 • 11-5 기타 함수 YES C 제 11 장 표준라이브러리

  3. 표준 라이브러리 역할 및 종류 • 표준 라이브러리 역할 • 프로그래머에게 편리하게 사용할 수 있는 다양한 종류의 함수를 제공 • 표준 라이브러리 종류 • 입출력함수, 문자 및 문자열 함수, 수치함수, 시스템 함수 • 연관된 표준 헤더 파일 • 함수원형, 매크로 정의, 자주 사용하는 자료형, 구조체, 상수 등을 포함 YES C 제 11 장 표준라이브러리

  4. 문자 처리 함수 • 문자 처리 함수 역할 • 하나의 문자를 변환 또는 검사하며, 문자나 숫자를 입력받아 판별한 결과를 반환 • 함수 결과가 참인 경우에는 0 아닌 숫자, 그렇지 않으면 0을 반환 • 문자 처리 함수 종류 • 문자 검사 함수 • isalnum( ), isalpha( ), isascii( ), iscntrl( ), isdigit( ), islower( ), isprint( ), ispunct( ), isspace( ), isupper( ) 등 • 문자 변환 함수 • tolower( ), toupper( ) 등 • 필요한 헤더 파일 • <ctype.h> YES C 제 11 장 표준라이브러리

  5. 문자 처리 관련 함수들 YES C 제 11 장 표준라이브러리

  6. 문자 처리 함수들의 기능 YES C 제 11 장 표준라이브러리

  7. 문자 처리 함수 예제 11.1 • 자판으로부터 입력되는 문자가 숫자인지를 판별하는 프로그램을 작성하시오. • 프로그램 결과 #include<ctype.h> /*헤드파일*/ #include<stdio.h> main() { charch; /*변수선언 */ ch=getchar(); if(isdigit(ch))printf("%cisanumber\n",ch); else printf("%cisnotanumber\n",ch); } 11 11isanumber a aisnotanumber YES C 제 11 장 표준라이브러리

  8. 문자 처리 함수 예제 11.2 • 자판으로부터 입력되는 문자가 영문자인가를 판별하는 프로그램을 작성하시오. • 프로그램 결과 #include<ctype.h> #include<stdio.h> /*헤드파일*/ main() { charch; /*변수선언 */ printf("문자나숫자를입력하시오\n"); ch=getchar(); /*문자입력함수 */ if(isalpha(ch))/*영문자판별함수 */ printf("%cisalphacharacter\n",ch); else printf("%cisnotalphacharacter\n",ch); } a aisalphacharacter 5 5isnotalphacharacter YES C 제 11 장 표준라이브러리

  9. 문자 처리 함수 예제 11.3 • 자판으로부터 입력되는 문자가 소문자인지를 판별하는 프로그램을 작성하시오. • 프로그램 결과 #include<ctype.h> #include<stdio.h> /*헤드파일*/ main() { charch; printf("문자를입력하시오\n"); ch=getchar(); /*문자입력함수 */ if(islower(ch)) /*소문자판별함수 */ printf("%cisloweralphacharacter\n",ch); else printf("%cisnotloweralphacharacter\n",ch); } q Qisloweralphacharacter Q Qisnotloweralphacharacter YES C 제 11 장 표준라이브러리

  10. 문자 처리 함수 예제 11.4 • 자판으로부터 입력되는 소문자를 대문자로, 대문자를 소문자로 변환하는 프로그램을 작성하시오. • 프로그램 결과 #include<ctype.h> #include<stdio.h> main() { charch,ch1,ch2; /*변수선언 */ printf("문자를입력하시오\n"); ch=getchar(); /*문자입력함수 */ if(isupper(ch))/*대문자판별함수 */ {printf("%cisauppercase\n",ch); ch1=tolower(ch);/*대문자를소문자로변환 함수 */ printf("%cisalowercase\n",ch1); } else if(islower(ch))/*소문자판별함수 */ {printf("%cisalowercase\n",ch); ch2=toupper(ch); /*소문자를대문자로변환 함수*/ printf("%cisauppercase\n",ch2); } else printf("%cisnotalphacharacter\n",ch); } A Aisauppercase aisalowercase k kisalowercase Kisauppercase 7 7isnotalphacharacter YES C 제 11 장 표준라이브러리

  11. 문자열 처리 함수 • 문자열 처리 함수 역할 • 문자열을 조작하거나 복사, 연결, 비교, 검출하는 기능을 제공 • 문자열 처리 함수 종류 • strlen( ) 함수 : 문자열의 수를 보여줌 • strcpy( ) 함수 : 문자열을 복사함 • strcmp() : 두 문자열을 비교함 • 기타 • 문자 처리 함수 종류 • <string.h> YES C 제 11 장 표준라이브러리

  12. 문자열처리함수들 함수명 형식 기능 strlen() unsigned strlen(const char *str) str의 문자열 길이를 반환 strcat() char *strcat(char *str1, const char *str2) str1의 문자열에 str2의 문자열을 연결 strncat() char *strncat(char *str1, const char *str2, unsigned c) str1의 문자열에 str2 문자열의 선두 c개의 문자를 연결 strcmp() char *strcmp(char *str1, const char *str2) str1의 문자열과 str2를 서로 부호없는 비교 str1>str2이면 양수값 반환 str1<str2이면 음수값 반환 str1=str2이면 0을 반환 strncmp() char *strcpy(char *str1, const char *str2, unsigned c) str1 문자열의 선두 c개의 문자와 str2의 문자열을 비교 strcpy() char *strcpy(char *str1, const char *str2, unsigned c) str1의 문자열에 str2의 문자열을 복사 strncpy() char *strncpy(char *str1, const char *str2, unsigned c) str1의 문자열에 str2 문자열의 선두 c개의 문자를 복사 strstr() char *strrstr(const char *str1 const char *str2) str1의 문자열에서 str2의 문자열을 출력 strerror() char *strerror(int num) 오류번호 num를 받아 해당하는 오류메시지를 반환 strpbrk() char *strpbrk(char *str1, const char *str2) 지정한 str1의 문자열에서 str2의 문자열에 포함된 어떤 문자를 찾고 위치의 포인터를 반환 strrchr() char *strrchr(const char *str, int c) 문자열 str의 끝 문자부터 시작하여 전방으로 진행하면서 문자 c를 찾아 그 위치의 포인터를 반환 YES C 제 11 장 표준라이브러리

  13. 함수명 형식 기능 strcspn() char *strcspn(char *str1, const char *str2) str1의 문자열에서 str2의 문자열에 포함된 문자가 첫 번째 나타날 때까지의 문자수 strspn() char *strspn(char *str1, const char *str2) str1의 문자열에서 str2의 문자열에 포함되지 않은 문자가 첫 번째 나타날 때까지의 문자수 strtok() char *strtok(char *str1, const char *str2) 분리 기호로 의미하는 str2의 각 문자를 이용하여 str1의 문자열를 의미있는 단위로 분리 strupr() char *strupr(char *str) 지정한 str의 문자열 중 소문자를 대문자로 변환 문자열 처리 함수들(계속) YES C 제 11 장 표준라이브러리

  14. 문자열 처리 함수 예제 11.5 • 문자열 “UNIVERSITY“을 복사하고, 길이를 구하는 프로그램을 작성하시오. • 프로그램 결과 #include<stdio.h> /*헤드파일*/ #include<string.h> main() /*함수이름 */ { intlen; /*변수선언 */ chars[20]; /*배열선언 */ strcpy(s,"CHEONANUNIVERSITY"); /*문자열복사함수 */ printf("%s\n\n",s); /*출력함수 */ len=strlen(s); printf("%d\n\n",len); /*문자열길이함수 */ } CHEONANUNIVERSITY 18 YES C 제 11 장 표준라이브러리

  15. 문자열 처리 함수 예제 11.6 • 자판으로부터 입력되는 두 문자열을 연결하는 프로그램을 작성하시오. • 프로그램 결과 #include<string.h> /*헤드파일*/ #include<stdio.h> main() /*함수이름 */ { charstr1[20],str2[20]; /*배열선언 */ printf("Entertwostrings:\n"); scanf("%s",str1); /*문자열입력함수 */ scanf("%s",str2); /*문자열입력함수 */ strcat(str1,str2); /*문자열연결함수 */ printf("%s\n",str1); } Entertwostring: Cheonan University CheonanUniversity YES C 제 11 장 표준라이브러리

  16. 문자열 처리 함수 예제 11.7 • 문자열“this is a test sentence”에서 문자열 “sentence“만 화면에 출력하는 프로그램을 strstr() 함수를 이용하여 작성하시오. • 프로그램 결과 #include<string.h> #include<stdio.h> main() { char*p,*str1="Thisisatestsentence"; char*str2="se"; p=strstr(str1,str2); /*str1의문자열에서str2의문자열을출력*/ printf("%s\n",p); } sentence YES C 제 11 장 표준라이브러리

  17. 문자열 처리 함수 예제 11.8 • 자판으로부터 입력되는 문자열이 "login"이면 “success”를, 다른 문자열일 경우에는 “failure”를 화면에 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<string.h> #include<stdio.h> main() { charpass[20]; /*배열선언 */ printf("Enterpassword:\n"); scanf("%s",pass); if(strcmp(pass,"login")) /*문자열비교함수 */ printf("Failure\n"); else printf("Success\n"); } Enterpassword: test Failure login Success YES C 제 11 장 표준라이브러리

  18. 문자열 처리 함수 예제 11.9 • 문자열 “March. 30, 2002”에서 문자 '.', ','가 포함되어 있는 지를 확인하고, 어느 하나라도 찾게 될 경우 첫 번째 문자의 위치를 가리키는 포인터 값을 구하는 프로그램을 strpbprk() 함수를 이용하여 작성하시오. • 프로그램 결과 #include<stdio.h> #include<string.h> main() { char*ptr; char*str1="March.30,2002"; char*str2=".,"; ptr=strpbrk(str1,str2); /*지정한str1의문자열에서str2의문자열에포함된어 떤문자를찾고위치의포인터반환함수*/ printf("point=%d\n",ptr); printf("char=%c\n",*ptr); } point=4325421 char=. YES C 제 11 장 표준라이브러리

  19. 문자열 처리 함수 예제11.10 • 문자열“March. 30, 2002” 에서 끝 문자부터 시작하여 전방으로 진행하면서 문자 ‘.’를 찾아 첫 번째 나타나는 위치 포인터 값을 구하는 프로그램을 strrchr() 함수를 이용하여 작성하시오. • 프로그램 결과 #include<stdio.h> #include<string.h> main() { char*ptr; char*str1="March.30,2002"; charch1='.'; ptr=strrchr(str1,ch1); /*지정한str1의문자열에서ch1의문자를찾아그위치 의포인터반환함수*/ printf("point=%d\n",ptr); printf("char=%c\n",*ptr); } point=4325441 char=. YES C 제 11 장 표준라이브러리

  20. 문자열 처리 함수 예제11.11 • 문자열“March.30, 2002”에서 문자 ‘.’가 첫 번째 나타날 때까지의 문자수를 화면에 출력하는 프로그램을 strcspn() 함수를 이용하여 작성하시오. • 프로그램 결과 #include<stdio.h> #include<string.h> main() { intlen; char*str1="March.30,2002"; char*str2="."; len=strcspn(str1,str2); /*str1의문자열에서str2의문자열에포함된문자가첫번째나타날때까지의문자수출력함수*/ printf("length=%d\n",len); } length=5 YES C 제 11 장 표준라이브러리

  21. 기억장치 관리 함수 • 기억장치 함수 역할 • 컴퓨터의 기억공간을 할당, 해제, 주소값을 반환하는 기능을 수행 • 동적 메모리 할당(Dynamic Memory Allocation) • 프로그램을 진행하는 도중에 필요에 따라서 메모리를 할당하는 것 • 포인터와 연계하여 사용 • 기억장치 함수 종류 • malloc( )와 calloc( ) • 지정한 기억 공간의 메모리의 크기만큼을 할당하여 반환 • free( ) • 가능한 재생을 위해 미리 할당된 기억 공간을 해제하며, 그 공간은 힙으로 반송 • malloc(size) • size 바이트의 기억공간 블록을 할당하고, 성공적으로 호출할 경우에는 기억공간의 주소를 반환 • calloc( n, size) • n개인 배열을 위해 연속된 기억공간을 할당 • malloc()과 차이점 : 할당하고 난 후 메모리를 0으로 초기화 • 필요한 헤더 파일 • <stdlib.h>와 <alloc.h> YES C 제 11 장 표준라이브러리

  22. 함수명 형식 기능 calloc() void *malloc(unsigned n, unsigned size) size 바이트 크기의 n개 기억공간을 확보한 후 그 내용을 0으로 초기화 malloc() void *malloc(unsigned size) size 만큼의 바이트에 해당하는 기억공간을 할당하고, 그것에 대한 포인터를 반환 free() void *free(void *ptr) ptr로 지정된 기억공간을 사용할 수 있도록 해제 realloc() void *realloc(void *ptr, unsigned size) ptr로 지정된 기억공간을 size 크기로 다시 변경 기억 장치 관리 함수의 형식과 기능 YES C 제 11 장 표준라이브러리

  23. 기억장치 관리 함수 예제 11.12 • 10 바이트의 기억 공간을 확보하여 "Hello" 문자열에 할당하고 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<stdio.h> #include<string.h> #include<malloc.h> #include<process.h> intmain(void) { char*str; if((str=(char*)malloc(10))==NULL) /*문자열에메모리할당*/ { printf("메모리할당실패\n"); exit(1); /*메모리가부족한경우프로그램밖으로*/ } strcpy(str,"Hello"); /*"Hello"문자열을str에복사함수*/ printf("Stringis%s\n",str);/*출력함수 */ free(str);/*메모리사용해제함수*/ return0; } StringisHello YES C 제 11 장 표준라이브러리

  24. 기억장치 관리함수 예제11.13 • 5개의 변수에 대해 128 바이트 기억 공간을 확보하고, 만약 기억 공간을 할당받지 못할 경우 “메모리 할당 실패” 메시지와 함께 프로그램에서 빠져나오고, 할당받을 경우에는 한 문자열을 자판을 통해 입력할 수 있는 프로그램을 작성하시오. • 프로그램 결과 #include<stdlib.h> #include<stdio.h> intmain(void) { char*str[5]; inti; for(i=0;i<5;i++) {if((str[i]=malloc(128))==NULL) {printf("메모리할당실패\n"); exit(0); } printf("메모리할당성공,문자열[%d]을입력하시오. \n",i+1); gets(str[i]); } for(i=0;i<5;i++) free(str[i]); } 메모리할당성공,문자열[1]을입력하시오. cheonan 메모리할당성공,문자열[2]을입력하시오. university 메모리할당성공,문자열[3]을입력하시오. information 메모리할당성공,문자열[4]을입력하시오. communication 메모리할당성공,문자열[5]을입력하시오. engineering YES C 제 11 장 표준라이브러리

  25. 자료 변환 처리 함수 • 자료 변환 처리 함수 역할 • 문자열을 변환 문자를 사용하여 편집하거나, 수치 자료로 변환하는 기능을 제공 • 함수 결과가 참인 경우에는 0 아닌 숫자, 그렇지 않으면 0을 반환 • 자료 변환 처리 함수 종류 • 문자 검사 함수 • isalnum( ), isalpha( ), isascii( ), iscntrl( ), isdigit( ), islower( ), isprint( ), ispunct( ), isspace( ), isupper( ) 등 • 문자 변환 함수 • tolower( ), toupper( ) 등 • 필요한 헤더 파일 • <stdlib.h> YES C 제 11 장 표준라이브러리

  26. 함수명 형식 기능 atoi() int atoi(const char *str) str의 문자열을 int형 정수로 변환 atol() int atol(const char *str) str의 문자열을 long형 정수로 변환 atof() double atof(const char *str) str의 문자열을 double형 실수로 변환 itoa() char *itoa(const int val, char *str, int rad) 정수 val를 문자열로 변환하여 str에 저장 qsort() void qsort(void *base, unsigned num, unsigned size, int(*compare)(const void*, const void*)) quick sort 방식으로 compare가 가리키는 비교 함수를 이용하여 데이터를 정렬 bsearch() void *bsearch(const void *key,const void *base, unsigned num, unsigned size, int(*compare)(const void *, const void *)) 정렬된 base의 size개의 원소 중에서 key로 지정한 원소를 이진 검색 방법으로 검색 자료 변환 처리 함수의 형식과 기능 YES C 제 11 장 표준라이브러리

  27. 자료변환 처리 함수 예제 11.14 • 자판으로부터 두 문자열을 입력받고, 이것을 double형 실수로 변환하여 합하는 프로그램을 작성하시오. • 프로그램 결과 #include<stdlib.h> #include<stdio.h> main() { charnum1[80],num2[80]; printf("Enterfirst:\n"); gets(num1); /*문자열을입력함수*/ printf("Entersecond:\n"); gets(num2); printf("Thesumis:%f\n",atof(num1)+atof(num2)); /*num1과num2의문자열을double형실 수로변환하는함수*/ } Enterfirst: 23 Entersecond: 35 Thesumis:58.000000 YES C 제 11 장 표준라이브러리

  28. 자료변환 처리 함수 예제 11.15 • 자판으로부터 두 문자열을 입력받고, 이것을 int형 정수로 변환하여 합하는 프로그램을 작성하시오. • 프로그램 결과 #include<stdlib.h> #include<stdio.h> intmain(void) { charnum1[80],num2[80]; printf("Enterfirst:\n"); gets(num1); printf("Entersecond:\n"); gets(num2); printf("Thesumis:%d\n",atoi(num1)+atoi(num2)); /*num1과num2의문자열을정수로변환하는함수*/ } Enterfirst: 23 Entersecond: 35 Thesumis:58 YES C 제 11 장 표준라이브러리

  29. 자료변환 처리 함수 예제 11.16 • 자판으로부터 두 문자열을 입력받고, 이것을 long형 정수로 변환하여 합하는 프로그램을 작성하시오. • 프로그램 결과 #include<stdlib.h> #include<stdio.h> intmain(void) { charnum1[80],num2[80]; printf("Enterfirst:\n"); gets(num1); printf("Entersecond:\n"); gets(num2); printf("Thesumis:%d\n",atol(num1)+atol(num2)); /*num1과num2의문자열을long형정수 로변환하는함수*/ } Enterfirst: 2300000 Entersecond: 3500000 Thesumis:5800000 YES C 제 11 장 표준라이브러리

  30. 산술(수학) 함수 • 산술 함수 역할 • 계산 프로그램을 할 때 사용할 수 있도록 지원 • 산술 함수 종류 • 문자 검사 함수 • isalnum( ), isalpha( ), isascii( ), iscntrl( ), isdigit( ), islower( ), isprint( ), ispunct( ), isspace( ), isupper( ) 등 • 문자 변환 함수 • tolower( ), toupper( ) 등 • 필요한 헤더 파일 • <math.h> YES C 제 11 장 표준라이브러리

  31. 산술함수 함수명 형식 기능 sin(x) double sin(double x) sine 함수 제공 cos(x) double cos(double x) cosine함수 제공 tan(x) double tan(double x) tangent 함수 제공 fmod(x) double fmod(double x, double y) double 형 부동 소수점수를 x/y한 나머지 log(x) double log(double x) 자연대수 log x 제공 1og10(x) double log10(double x) 상용대수 log10 x 제공 exp(x) double exp(double x) 지수함수 제공 asin(x) double asin(double x) arch sine 함수 제공 acos(x) double acos(double x) arch cosine 함수 제공 atan(x) double atan(double x) arch tangent 함수 제공 pow(x,y) double pow(double x, double y) x를 y승 sqrt(x) double sqrt(double x) 양의 제곱근SQRT { x} YES C 제 11 장 표준라이브러리

  32. 함수명 형식 기능 abs(x) int abs(int x) x의 절대값 제공 floor double floor(double x, double y) 부동 소수점 x의 소수점 이하를 전달하여 버린 수 ceil double ceil(double x) 부동 소수점 x의소수점 이하를 올림한 수를 구함. rand() int rand() 0에서 32767 사이의 연속적인 난수 제공 srand() void srand(unsigned seed) 난수 발생 함수의 난수 발생 시작 값 seed을 변경하여 설정 산술함수(계속) YES C 제 11 장 표준라이브러리

  33. 산술 함수 예제 11.17 • 자판으로부터 입력하는 정수(x)의 제곱근을 구하는 프로그램을 작성하시오. • 프로그램 결과 #include<math.h> #include<stdio.h> main() { intx; doubley; printf("Inputdata:\n"); scanf("%d",&x); y=sqrt(x); printf("Squarerootofx=%f",y); } Inputdata: 16 Squarerootofx=4 YES C 제 11 장 표준라이브러리

  34. 산술 함수 예제 11.18 • 1에서 1까지 값에 대한 sine, cosine, tangent 값을 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<math.h> #include<stdio.h> main() { doubleval=-1.0; do{ printf("sineof%fis%f\n",val,sin(val)); /* sine함수 */ printf("cosineof%fis%f\n",val,cos(val)); /* cosine함수 */ printf("tangentof%fis%f\n",val,tan(val)); /* tangent함수 */ val+=1; }while(val<=1.0); return0; } sineof-1.000000is-0.841471 cosineof-1.000000is0.540302 tangentof-1.000000is-1.557408 sineof-0.000000is-0.000000 cosineof-0.000000is1.000000 tangentof-0.000000is-0.000000 sineof1.000000is0.841471 cosineof1.000000is0.540302 tangentof1.000000is1.557408 YES C 제 11 장 표준라이브러리

  35. 산술 함수 예제 11.19 • 1에서 1까지 값에 대한 arc sine, cosine, tangent 값을 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<math.h> #include<stdio.h> main() { doubleval=1.0; do{ printf("value[%f]arcsine[%f]\n",val,asin(val)); /* archsine함수 */ printf("arccosine[%f]\n",acos(val)); /* archcosine함수 */ printf("arctangent[%f]\n",atan(val)); /* archtangent함수 */ val-=1; }while(val>=-1.0); } value[1.000000]arcsine[1.570796] arccosine[0.000000] arctangent[0.785398] value[0.000000]arcsine[0.000000] arccosine[1.570796] arctangent[0.000000] value[-1.000000]arcsine[-1.570796] arccosine[3.141593] arctangent[-0.785398] YES C 제 11 장 표준라이브러리

  36. 산술 함수 예제 11.20 • 1에서 1까지 값에 대한 log x의 자연 대수와 log10의 상용 대수를 구하는 프로그램을 작성하시오. • 프로그램 결과 #include<math.h> #include<stdio.h> main() { doubleval=1.0; do { printf("value[%f]log[%f]",val,log(val)); printf("log10[%f]\n",log10(val)); val++; } while(val<11.0); } value[1.000000]log[0.000000]log10[0.000000] value[2.000000]log[0.693147]log10[0.301030] value[3.000000]log[1.098612]log10[0.477121] value[4.000000]log[1.386294]log10[0.602060] value[5.000000]log[1.609438]log10[0.698970] value[6.000000]log[1.791759]log10[0.778151] value[7.000000]log[1.945910]log10[0.845098] value[8.000000]log[2.079442]log10[0.903090] value[9.000000]log[2.197225]log10[0.954243] value[10.000000]log[2.302585]log10[1.000000] YES C 제 11 장 표준라이브러리

  37. 산술 함수 예제 11.21 • 자판에서 입력된 수를 절대값을 구하는 프로그램을 작성하시오. • 프로그램 결과 #include<math.h> #include<stdio.h> main() { inta,b; printf("숫자를입력하시오.\n"); scanf("%d",&a); b=abs(a); printf("|%d|=%d\n",a,b); } 숫자를입력하시오. -31 |-31|=31 YES C 제 11 장 표준라이브러리

  38. 산술 함수 예제 11.22 • 자판에서 입력된 수를 seed 값으로 하여 난수를 구하는 프로그램을 작성하시오. • 프로그램 결과 #include<stdio.h> #include<stdlib.h> voidmain() { inti,a; scanf("%d",&a); srand(a); /*난수발생함수의난수발생시작값seed을설정하는함수*/ for(i=1;i<=5;i++) printf("%d\n",rand()); /*0에서32767사이의연속 적인난수제공하는함수 */ } 35 152 23465 23892 25453 9417 YES C 제 11 장 표준라이브러리

  39. 시간 관련 함수 • 시간 함수 역할 • 시스템의 시간이나 그리니치 표준 시간, 날짜 등을 얻고자 할 경우 사용되는 함수 • 시간 함수 종류 • localtime(), gmtime(), ctime(), • difftime( ), ftime() • 필요한 헤더 파일 • <time.h> YES C 제 11 장 표준라이브러리

  40. 함수명 형식 기능 localtime() struct tm *localtime(const time_t *t) time() 함수에 의해 구한 시간을 시스템의 현재 시간으로 저장 gmtime() struct tm *gmtime(const time_t *t) time() 함수에 의해 구한 시간을 그리니치 표준시간으로 저장 ctime() char *ctime(const time_t *t) time() 함수를 이용하여 구한 시스템 시간 t를 현재 시간으로 표시할 수 있는 문자열로 변환 difftime( ) double difftime(time_t t1, time_t t2) time() 함수에 의해 구한 시간 t1과 t2 간의 시간 차이를 초로 계산 ftime void ftime(struct timeb *buf) tzset()함수를 호출하여 현재 시간을 buf에 의해 지정된 구조체 timeb의 각 필드에 저장 시간 관련 함수 YES C 제 11 장 표준라이브러리

  41. 시간 관련 함수 예제 11.23 • ctime() 함수를 이용하여 현재 시간을 문자열로 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<time.h> #include<stdio.h> voidmain() { time_tt; t=time(NULL); printf("Today'sdataandtime:%s\n",ctime(&t)); } Today'sdataandtime:TueJan1415:58:252003 YES C 제 11 장 표준라이브러리

  42. 시간 관련 함수 예제 11.24 • localtime() 함수를 이용하여 시스템의 현재 시간을 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<time.h> #include<stdio.h> intmain(void) { structtm*ptr; time_tlt; lt=time(NULL); ptr=localtime(&lt); printf(asctime(ptr)); } TueJan1415:59:022003 YES C 제 11 장 표준라이브러리

  43. 시간 관련 함수 예제 11.25 • localtime()와 gmtime() 함수를 이용하여 현지 시간과 그리니치 표준시간을 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<time.h> #include<stdio.h> intmain(void) { structtm*local,*gm; time_tt; t=time(NULL); local=localtime(&t); printf("Localtimeanddata:%s",asctime(local)); gm=gmtime(&t); printf("Greenwichmeantimeanddata:%s",asctime(gm)); } Localtimeanddata:TueJan1415:59:492003 Greenwichmeantimeanddata:TueJan1406:59:492003 YES C 제 11 장 표준라이브러리

  44. 실습 문제 1 • isalpha()함수를 이용하여 알파벳 대/소문자를, isdigit()와 ispunct( )함수를 이용하여 숫자와 특수 문자를 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<stdio.h> #include<ctype.h> main() { intc; printf("\nisalpha:\n"); for(c=0;c<127;c++) if(isalpha(c))putchar(c); printf("\nisdigit:\n"); for(c=0;c<127;c++) if(isdigit(c))putchar(c); printf("\nispunct:\n"); for(c=0;c<127;c++) if(ispunct(c))putchar(c); } isalpha: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz isdigit: 0123456789 ispunct: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ Pressanykeytocontinue YES C 제 11 장 표준라이브러리

  45. 실습 문제 2 • 너의 이름과 암호를 입력할 때 만약 틀린 경우 “invalid password”메시지를, 성공하면 “success" 메시지를 출력하는 프로그램을 작성하시오. • 프로그램 결과 #include<stdio.h> #include<string.h> main() {chara[30],b[30],pass[10],s1[15],s2[15]; printf("/*strcat()=string1+string2*/\n\n"); printf("Yourfirstname:");gets(a); printf("Yourlastname:");gets(b); printf("\n\nYourname=firstname+lastname=%s\n",strcat(a,b)); printf("\n\n/*strcmp()=comparestring1withstring2*/\n"); printf("\n\nifyourpasswordis....lee123\n"); do{printf("YourPassword:");gets(pass); if(strcmp(pass,"lee123")) printf("invalidpassword\n"); else break; }while(1); printf("\nsuccess"); printf("\n/*strcpy(s1,s2)=Copys2tos1*/\n"); printf("inputmemo:");gets(s2); strcpy(s1,s2); printf("s1=%s\n",s1); } /*strcat()=string1+string2*/ Yourfirstname:lee Yourlastname:sunsin sYourname=firstname+lastname=leesunsin /*strcmp()=comparestring1withstring2*/ ifyourpasswordis....h6614 YourPassword:kjhjkhk invalidpassword YourPassword:lee123 success /*strcpy(s1,s2)=Copys2tos1*/ inputstrings2:I'mastudent! s1=I'mastudent! YES C 제 11 장 표준라이브러리

  46. 실습 문제 3 • 산술 함수를 이용하여 0, 15, 30, 45, 60, 75, 90에 대한 sine, cosine, tangent 값을 구하고, 자판으로 입력된 값에 대해 제곱근, 자승, log 값을 구하는 프로그램을 작성하시오. YES C 제 11 장 표준라이브러리

  47. 프로그램 결과 #include<stdio.h> #include<conio.h> #include<math.h> #definePi3.141592 voidmain() {inta,b; floatx,y,p,lo; clrscr(); printf("x\tsin(x)cos(x)tan(y)\n"); for(x=0;x<=90;x=x+15){ y=x*Pi/180; printf("%6.2f%12.5f%12.5f%12.5f\n",x,sin(y), cos(y),tan(y)) } printf("\tPressanykey......."); getch(); printf("\n***Root***\n"); printf("input(x):"); scanf("%f",&p); printf("sqrt(%f)=%f\n\n",p,sqrt(p)); printf("***a^b***\n"); printf("input(a,b):"); scanf("%d%d",&a,&b); printf("%d^%d=%f\n\n",a,b,pow(a,b)); printf("***log10(x)***\n"); printf("input(x):"); scanf("%f",&lo); printf("log10(%f)=%f\n",lo,log10(lo)); printf("\tPressanykey......."); getch();} xsin(x)cos(x)tan(y) 0.000.000001.000000.00000 15.000.258820.965930.26795 30.000.500000.866030.57735 45.000.707110.707111.00000 60.000.866030.500001.73205 75.000.965930.258823.73205 90.001.000000.000003185560.70806 Pressanykey....... ***Root*** input(x):16 sqrt(16.000000)=4.000000 ***a^b*** input(a,b):25 2^5=32.000000 ***log10(x)*** input(x):100 log10(100.000000)=2.000000 Pressanykey....... YES C 제 11 장 표준라이브러리

  48. 실습 문제 3 • 2차 방정식 ax2 + bx + c = 0에서 a, b, c를 입력받아 그 근을 구하는 함수 root()를 작성하시오. 이때 무한루프를 이용하고 ‘q'를 치면 루프를 빠져나가도록 작성하시오. m = b*b - 4 * a * c if m < 0 허근 m = 0 중근 m > 0 서로 다른 두 근 YES C 제 11 장 표준라이브러리

  49. 프로그램 결과 #include<stdio.h> #include<conio.h> #include<math.h> root(inta,intb,intc) {intm; floaty,y1,y2; m=b*b-4*a*c; printf("a=%db=%dc=%dm=%d\n",a,b,c,m); if(m<0) printf("rootisnon\n"); elseif(m==0) {y=(-b+sqrt(m))/(2*a); printf("y=%f\n",y); } else{y1=(-b+sqrt(m))/(2*a); y2=(-b-sqrt(m))/(2*a); printf("y1=%f\n",y1); printf("y2=%f\n",y2); } } voidmain() { inta,b,c,z; printf("2차방정식근구하기\n"); do{ printf("\ninput(a,b,c):"); scanf("%d%d%d",&a,&b,&c); root(a,b,c); printf("pressanykey...or'q'toexit"); c=getchar(); c=getchar(); }while(c!='q'); } 2차방정식근구하기 input(a,b,c):253 a=2b=5c=3m=1 y1=-1.000000 y2=-1.500000 pressanykey...or'q'toexit input(a,b,c):1-44 a=1b=-4c=4m=0 y=2.000000 pressanykey...or'q'toexit input(a,b,c):234 a=2b=3c=4m=-23 rootisnon pressanykey...or'q'toexit input(a,b,c):156 a=1b=5c=6m=1 y1=-2.000000 y2=-3.000000 pressanykey...or'q'toexitq YES C 제 11 장 표준라이브러리

  50. 실습 문제 3 • bioskey()함수를 이용한 프로그램이다. 키보드에서 키를 입력하면 그 키를 출력해주고 Ctrl + 키, Alt + 키, Shift + 키를 입력하여도 이를 인식하여 출력하는 프로그램을 작성하시오. YES C 제 11 장 표준라이브러리

More Related