전기전자공학/프로젝트

[Kernighan - C] #4-1,2 함수의 기초

LinZBe4hia 2017. 6. 26. 11:49

4.1 함수의 기초



[예제 4-1]

s내에서 t의 가장 오른쪽 위치를 나타내는 함수 strindex(s,t)를 작성해보라. 만일 t가 없다면 -1을 리턴.

(맨 오른쪽 기준을 0으로 한 경우)

1
2
3
4
5
6
7
8
9
10
11
int strindex(char s[], char t[]) {
    int i, j, k;
 
    for (i = 0; s[i] != '\0'; i++) {
        for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
            ;
        if (k > 0 && t[k] == '\0')
            return strlen(s) - (i+ strlen(t)) - 1;
    }
    return -1;
}
cs


strlen(s)는 실제 s에서 \n을 포함한 길이 이므로 실제 s의 길이(눈에 보이는 문자와 공백들)는 strlen(s) -1이다.

(i + strlen(t) - 1)은 맨 왼쪽을 0으로 했을 때 t의 맨 오른쪽 단어의 위치를 나타내는 수식이다.

(strlen(s) - 1) - (i + strlen(t) - 1)을 하면 맨 오른쪽이 index = 1인 기준이므로, 

나같은 경우 최우측을 0으로 기준을 삼았으니 최종식에다 -1일 빼줘야 한다.

따라서,  (strlen(s) - 1) - (i + strlen(t) - 1)  - 1 = strlen(s) - (i+ strlen(t)) -1



[예제 4-2]

소수 뒤에 e나 E가 나오고, 그 뒤에는 부호 생략이 가능한 지수부분이 오도록 atof 함수를 확장하여 프로그램을 작성하여라. 

즉 123.45e-6와 같은 형태의 수를 다룰 수 있도록 atof함수를 확장하라.

작성 파일: main.c, atof.c, power.c, hi.h

Make파일: Makefile


main.c

1
2
3
4
5
6
#include "hi.h"
 
main() {
    char str[100= "12.3e-6";
    printf("%lf\n", atof(str));
}
cs

atof.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "hi.h"
 
/* atof: convert string s to double */
double atof(char s[]) {
    double val, power;
    int i, sign, n; // n: 자릿수
 
    for (i = 0; isspace(s[i]); i++/* skip white space */
        ;
 
    sign = (s[i] == '-') ? -1 : 1;
 
    if (s[i] == '+' || s[i] == '-')
        i++;
    for (val = 0.0; isdigit(s[i]); i++)
        val = 10.0 * val + (s[i] - '0');
    if (s[i] == '.')
        i++;
    for (power = 1.0; isdigit(s[i]); i++) {
        val = 10.0 * val + (s[i] - '0');
        power *= 10.0;
    }
    if (s[i] == 'e') {
        i += 2;
        n = s[i] - '0';
    }
    return sign *(val / power) * power1(10, n);
}
cs

power.c

1
2
3
4
5
6
7
8
9
10
11
#include "hi.h"
 
/* power: raise base to nth power */
int power1(int base, int n)
{
    int p;
 
    for (p = 1; n > 0--n)
        p *= base;
    return p;
}
cs

hi.h

1
2
3
4
5
#include <stdio.h>
#include <ctype.h>
 
double atof(char[]);
int power1(int base, int n);
cs