Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 이번 시간에는 형변환에 대해서 알아보도록 한다.
- * 여러가지 변환들이 있다.
- * 1. 문자열에서 숫자로.
- * 2. 문자 타입을 변경. double -> int...
- * 3. 부호가 있는 것 <--> 부호가 없는 것.
- *
- *
- * 산술 연산에서는 묵시적 형변환이 일어난다.
- * - 만약 연산대상 중에서 하나라도 long double 형이 있다면, 다른 것들은 long double형으로 변환.
- * - 그렇지 않다면, 만약 연산대상 중에서 하나라도 double 형이 있다면, 다른 것들은 double형으로 변환.
- * - 그렇지 않다면 하나로도 float 형이 있다면 다른 것들은 float 형으로 변환.
- * - 그렇지 않다면, char 와 short는 int으로 변환된다.
- * - 그런다음, 연산대상 중에서 하나라도 long형이 있다면, 다른 것들은 long형으로 변환된다.
- *
- * * 한가지 유의할 점은 float 형은 자동적으로 double 형으로 변환되지 않는다.
- */
- #define RAND 0
- #define ATOI 1
- #if RAND
- /*
- * Generate a random number.
- * The example of rand.
- */
- #include <stdio.h>
- #define KEY 1103515245L
- #define SOLT 12345L
- unsigned long int next = 1;
- int rand (void)
- {
- next = next * KEY + SOLT;
- /* the return type of sizeof could be unsigned long int.*/
- printf("%lu\n", sizeof(unsigned int));
- return (unsigned int) (next/65536) % 32768;
- }
- int main (int argc, char** argv)
- {
- unsigned int val;
- val = rand();
- printf("%u\n", val);
- return 0;
- }
- // the water is wild.
- #endif
- #if ATOI
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <assert.h>
- #define MAX_LEN 6
- /*
- * Let's make atoi function.
- */
- int is_digit_me (char c)
- {
- return (c <= '9') && (c >= '0') ? 1 : 0;
- }
- int atoi_me (const char* s)
- {
- int i;
- int total = 0;
- char c;
- for (i = 0; i < strlen(s); i++) {
- c = s[i];
- if (is_digit_me(c)) {
- total *= 10;
- total += c - '0';
- }
- else {
- assert(0);
- }
- }
- return total;
- }
- char* input_msg(void)
- {
- int i = 0;
- char c;
- char* buf = NULL;
- // memset
- buf = (char*)malloc(sizeof(char) * MAX_LEN);
- memset(buf, 0, MAX_LEN);
- // while ((c = getchar()) != '\n') {
- for (i = 0; ((c = getchar()) != '\n'); i++) {
- if (i == MAX_LEN) {
- break;
- }
- if (is_digit_me(c) == 0){
- goto free_buf;
- }
- buf[i] = c;
- }
- return buf;
- free_buf:
- free(buf);
- return NULL;
- }
- int main (int argc, char** argv)
- {
- const char* string_num = "30213";
- char* buf = NULL;
- int ret = 0;
- // mem alloc from input_msg()
- buf = input_msg();
- if (buf == NULL) {
- assert(0);
- }
- ret = atoi_me(buf);
- printf("%d\n", ret);
- // free
- free(buf);
- return 0;
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement