<C프로그래밍-새내기를 위한 첫 C 언어 책>연습문제 chapter 6 (7,8,9,10)

7. 1~n의 정수를 각각 제곱하여 합한 결과를 구하는 프로그램을 작성하시오. 각 정수의 제곱을 구하는 기능은 매크로로 구현한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#define SQ(x) ((x)*(x))
int main(void)
{
    int n, i = 1, sum = 0;
    printf("n의 값을 입력하세요: ");
    scanf_s("%d"&n);
 
    for (i = 1; i <= n; i++)
    {
        if (i < n) printf("%d + ", i);
        else printf("%d = ", i);
        sum += SQ(i);
    }
    printf("%d", sum);
 
    return 0;
}
cs

i가 n보다 작을 때는 '숫자+' 를 출력하고 같을 때는 '숫자='을 출력하여 등식을 완성한다.

 

 

8. 구의 부피를 구하는 매크로 함수를 정의하고 키보드로 반지름을 입력받아 구의 부피를 구하는 프로그램을 작성하시오.

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#define PI 3.141592
#define VOLUME(r) ((4.0/3.0)*(PI)*(r)*(r)*(r))
int main(void)
{
    int radius;
    printf("반지름: ");
    scanf_s("%d"&radius);
    printf("반지름이 %d인 구의 부피 = %.2lf", radius, VOLUME(radius));
 
    return 0;
}
cs

 

 

 

9. 정수 두 개의 값을 바꾸는 매크로 함수 SWAP(x, y)를 작성하고 프로그램을 완성하시오.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#define SWAP(x, y, t) ( (t) = (x), (x) = (y), (y) = (t))
 
int main(void)
{
    int x, y, t;
    printf("두 수 입력: ");
    scanf_s("%d %d"&x, &y);
    SWAP(x, y, t);
    printf("%d %d", x, y);
 
    return 0;
}
cs

 

SWAP함수가 x, y 자체를 바꾸므로 x, y를 출력하면 값이 바뀌어 출력된다.

 

 

10. 5장의 [프로그램 5-7]은 질문의 답에 따라 해당 가산점을 계산하는 프로그램이다. 12행에서 1 대신 MALE을, 17, 23, 34행에서 1 대신 YES를 사용하도록 매크로 상수를 정의하여 프로그램을 수정하시오.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdio.h>
#define MALE 1
#define YES 1
 
int main(void)
{
    int gender, married, army, plus, children;
 
    plus = 0;
 
    printf("성별 (남:1, 여:2) ? ");
    scanf_s("%d"&gender);
 
    if (gender == MALE)
    {
        printf("군 제대 (예:1, 아니오:2) ? ");
        scanf_s("%d"&army);
 
        if (army == YES)
        {
            plus++;
 
            printf("결혼 (예:1, 아니오:2) ? ");
            scanf_s("%d"&married);
            if (married == YES)
            {
                plus++;
            }
        }
    }
    else
    {
        printf("결혼 (예:1, 아니오:2) ? ");
        scanf_s("%d"&married);
        if (married == YES)
        {
            plus++;
 
            printf("자녀수는? ");
            scanf_s("%d"&children);
            if (children == 1)
            {
                plus++;
            }
            else if (children >= 2)
            {
                plus += 2;
            }
        }
    }
 
    printf("\n>> 총 가산점은 %d점입니다.", plus);
 
    return 0;
}
cs