프로그래밍 언어 공부/C

변환 랜덤 라이브러리

CalebHong 2022. 1. 21. 14:21
SMALL

데이터 변환 라이브러리

함수

- atoi : 문자열정수(int)로 변환

- atof : 문자열실수(double)로 변환

- strtof : 실수 문자열float형 실수로 변환

- strtod : 실수 문자열double형 실수로 변환

 

예제)

atoi("2020"); // int형 2020으로 리턴

atoi("2020.123"); // int형 2020까지만 리턴

atoi(".,2020"); // 0을 리턴

 

활용 예제)

- 근무일 입력 시 급여 계산

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    char code[12] = "20080123-02";
    char year[5]; // 연도 + 널문자 까지 해서 5로 지정
    time_t timer;
    struct tm *t;
    int wDay = 25;
    int workYear, enYear, salary;
    strncpy(year, code, 4);
    enTear - atoi(year); // 당일 날짜를 가져옴
    timer = time(NULL);
    t = localtime(&timer);
    workYear = (t->tm_year + 1900)- enYear;
    salary = wDay * (workYear * 1000);
    
    printf("급여액 : %d", salary);
    
    return 0;
}

 

 

랜덤 함수 라이브러리

예제)

srand(time(NULL)); // 현재 시간을 난수 시드로 줌으로 항상 랜덤한 값을 받을 수 있음

 

 

활용예제)

- 학번에 따라 3개의 그룹으로 분류

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
	int i, std[10] = { 2017010, 2017014, 2017023, 2017034, 2017041, 
    				   2018002, 2018052, 2018154, 2022011, 2022015 }
   
   for (i = 0; i < 10; i++)
   {
   	srand(std[i]);
    printf("%d 번 은 그룹 %d\n", i+1, rand() % 3 + 1
   }
   
   return 0;
}

 

반응형