cyphen156

Chapter5 과제 본문

프로그래밍/C언어

Chapter5 과제

cyphen156 2023. 6. 21. 15:12

 

개인 문제풀이임으로 오답이 있을 수 있습니다.

  1. 아래 함수를 호출하여 입력 정수의 절댓값을 계산하는 프로그램을 작성하라. 단, 함수 내부에서 3항 연산자를 써야 한다. 입출력 형식은 자유로이 할 수 있다.
    int abs(int num);
    #define	_CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    int abs(int num);
    
    int main(void) {
    	int num;
    	scanf("%d", &num);
    	printf("%d", abs(num));
    	return 0;
    }
    
    int abs(int num) {
    	return 	(num >= 0) ? num : -num;
    }
  2. 아래 함수를 호출하되 알파벳 소문자 하나를 입력받아 그것이 자음이면 Consonant라고 출력하고 모음이면 Vowel이라고 출력하는 프로그램을 작성하라. 입출력 형식은 자유로이 할 수 있다.
    int is_vowel(char c)
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    void is_vowel(char c);
    
    int main(void) {
        char c;
        printf("소문자 하나를 입력하세요.\n");
        scanf("%c", &c);
        is_vowel(c);
        return 0;
    }
    
    void is_vowel(char c) {
        if (c < 'a' || c > 'z') {
            printf("소문자가 아닙니다.\n");
        }
        else {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
                printf("Vowel\n");
            else
                printf("Consonant\n");
        }
    }
  3. 단가(unit_price)와 개수(quantity)를 입력받아 총액(total_price)을 출력하는 프로그램을 작성하라. 단, 단가, 개수, 총액은 정수형이어야 한다. 개수가 10개를 넘을 때는 총액에서 5%를 할인한 금액을 출력해야 한다. 입출력 형식은 자유로이 할 수 있다.
    [hint] 0.95를 곱한 결과를 정수형으로 변환해야 한다.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    int calc(int price, int quan);
    
    int main(void) {
        int unit_price, quantity, total;
        printf("단가와 개수를 입력하세오.\n");
        scanf("%d %d", &unit_price, &quantity);
        total = calc(unit_price, quantity);
        printf("%d", total);
        return 0;
    }
    
    int calc(int price, int quan) {
        int result = price * quan;
        if (quan >= 10) {
            result *= 0.95;
        }
        return result;
    }
  4. 삼각형의 두 변의 길이 합은 항상 나머지 변의 길이보다 크다. 세 변의 길이를 입력받아 그것이 삼각형이 될 수 있으면 세 변의 길이 합을 출력하고 그렇지 않으면 'No such triangle'이라고 출력하는 프로그램을 작성하라. 단, 세 변의 길이는 모두 double 타입이다.
    > Enter three real numbers.
    > 0.0 0.0 0.0(Enter)
    > No such triangle.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    void calc(double a, double b, double c);
    
    int main(void) {
        double a, b, c;
        printf("Enter three real numbers.\n");
        scanf("%lf %lf %lf", &a, &b, &c);
        if (a <= 0 || b <= 0 || c <= 0) {
            printf("변의 길이는 항상 양수여야 합니다.\n");
            return 0;
        }
        calc(a, b, c);
        return 0;
    }
    
    void calc(double a, double b, double c) {
        if (a + b < c || b + c < a || c + a < b) {
            printf("No such triangle");
        }
        else
            printf("%lf", a + b + c);
    }
  5. 점 p의 정수형 좌표 값 x, y를 입력받아 그 점이 속한 4분면(quadrant)을 출력하는 프로그램을 작성하라. 단, 좌표축 경계선에 위치한 점은 입력하지 않기로 한다.
    > Enter the x, y coordinates of the point.
    > 4 -5(Enter)
    > It's in the 4th quadrant.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    void calc(int x, int y);
    
    int main(void) {
        int x, y;
        printf("Enter the x, y coordinates of the point.\n");
        scanf("%d %d", &x, &y);
        calc(x, y);
        return 0;
    }
    
    void calc(int x, int y) {
        if (x == 0 || y == 0) {
            printf("점은 사분면 위에 있지 않고 수직선 위에 존재합니다.");
        }
        else {
            if (x > 0) {
                if (y > 0)
                    printf("It's in the 1st quadrant.");
                else 
                    printf("It's in the 4th quadrant.");
            }
            else {
                if (y > 0)
                    printf("It's in the 2nd quadrant.");
                else
                    printf("It's in the 3rd quadrant.");
            }
        }
    }
     
  6. 체조 경기에서는 가장 낮은 점수와 가장 높은 점수를 제외한 나머지 점수만 평가에 반영한다. 문제를 단순화하여 3명의 심판이 1에서 10점까지 점수를 줄 경우 선수가 받는 점수를 계산해보라. 단, 세 심판이 모두 서로 다른 점수를 준다고 가정하라.
    [hint] 입력 점수 중 어느 하나가 최대이거나 최소이면 해당 점수를 0으로 놓아 덧셈 계산에서 제외할 수 있다.
    > Enter scores of three judges.
    > 10 5 7(Enter)
    > The player gets 7.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    void calc(int x, int y, int z);
    
    int main(void) {
        int a, b, c;
        printf("Enter scores of three judges.\n");
        scanf("%d %d %d", &a, &b, &c);
        if (0 < a && a < 11 && 0 < b && b < 11 && 0 < c && c < 11) {
            if (a == b || a == c) {
                printf("심판은 서로 다른 점수를 줘야 합니다.\n");
                return;
            }
            else
                calc(a, b, c);
        }
        else
            pritnf("심판이 줄 수 있는 점수는 1점부터 10점 사이입니다.");
        return 0;
    }
    
    void calc(int x, int y, int z) {
        if (x > y) {
            if (y > z) { // (x > y > z)
                x = 0;
                z = 0;
            }
            else {  // (x > z > y)
                x = 0;
                y = 0;
            }
        }
        else {  
            if (x > z) { // (y > x > z)
                y = 0;
                z = 0;
            }
            else {  // (y > z > x)
                y = 0;
                x = 0;
            }
        }
        printf("The player gets %d.", x + y + z);
    }
     
  7. scanf 문이 제대로 실행될 경우 읽어들인 변수의 개수를 돌려준다. 예를 들어, scanf("%c%d%lf", &sex, &age, &weight);가 제대로 실행되면 3을 돌려준다. 이 scanf가 제대로 실행되면 각각의 변수 값을 출력하고 그렇지 않을 경우 오류 메세지를 출력하는 프로그램을 if문을 써서 작성하라.
    > Enter sex, age, and weight.
    > F, 24, Soowon(Enter)
    > Error in input format.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    int main(void) {
        char sex;
        int age;
        double weight;
        // 아직 문자 배열에 대해 공부하지 않았으므로 한 문자만입력해야 정상적인 연산이 가능합니다.
        printf("Enter sex (M or F), age, and weight.\n"); 
        if (scanf("%c %d %lf", &sex, &age, &weight) != 3)
            printf("Error in input format.");
        else {
            printf("Sex: %c, Age: %d, Weight: %.2lf\n", sex, age, weight);
        }
        return 0;
    }
  8. 문자를 입력받아 그것이 알파벳인지 숫자인지 그 외의 경우인지 세 가지 경우로 구분하는 프로그램을 작성하라.
    [hint] 아스키코드 표에서 알파벳의 범위, 숫자의 범위를 참고하라, 숫자를 의미하는 문자(Digit)라면 if (ch >= '0' && ch <= '9')라고 할 수 있다.
    > Enter a character.
    > ;(Enter)
    > It is neither an alphaber nor a digit.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    void is_alpha(char c);
    
    int main(void) {
        char c;
        printf("Enter a character.\n"); 
        scanf("%c", &c);
        is_alpha(c);
        return 0;
    }
    
    void is_alpha(char c) {
        if (c >= '0' && c <= '9')
            printf("It is a digit.\n");
        else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
            printf("It is an alphabet\n");
        else
            printf("It is neither an alphaber nor a digit.\n");
    }
  9. 짝수인지 홀수인지 판정은 비트연산으로도 가능하다. 홀수의 2진 표현은 1로 끝나기 때문에 비트 단위로 1을 곱하면 1이 되기 때문이다. 예를 들어 11 & 1 == (1011) & (0001) == (0001) = 1이 된다. 숫자를 입력받아 &(Bitwise AND) 연산에 의해 그것이 짝수인지 홀수인지 판정하는 프로그램을 작성하라.
    > Enter an integer.
    > 201(Enter)
    > It is an odd number.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    void is_even_or_odd(int num);
    
    int main(void) {
        int num;
        printf("Enter an integer.\n");
        scanf("%d", &num);
        is_even_or_odd(num);
        return 0;
    }
    
    void is_even_or_odd(int num){
        if (num & 1)
            printf("It is an odd number.\n");
        else
            printf("It is an even number.\n");
    }
  10. 세 개의 문자로 이루어진 단어를 입력받아 그 중 숫자를 나타내는 문자는 몇 개인지 출력하는 프로그램을 작성하라. 단, 아래 함수를 작성하고 호출하여 ch가 숫자를 나타내는지 판정하라.
    int is_digit(int ch);

    > Enter a 3-letter word.
    > k16(Enter)
    > Digit appears 2 times.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    int is_digit(int ch);
    
    int main(void) {
        char ch[4];
        int cnt = 0;
        printf("Enter a 3-letter word.\n");
        scanf("%s", ch);
        for (int i = 0; i < 3; i++) {
            if (is_digit(ch[i])) {
                cnt++;
            }
        }
        printf("Digit appears %d times.\n", cnt);
        return 0;
    }
    
    int is_digit(int ch){
        if (ch >= '0' && ch <= '9')
            return 1;
        else
            return 0;
    }
  11. 윤년이란 2월이 29일까지 있는 해를 말한다. 이는 4로 나누어떨어지지만 100으로는 나누어떨어지지 않거나 4로 나누어떨어지는 동시에 400으로 나누어떨어지는 해를 말한다. 아래 함수를 사용하여 연도가 주어질 때 윤년인지 아닌지를 출력하는 프로그램을 작성하라.
    int leap_year(int y);
    > Enter year.
    > 2000(Enter)
    > It is a leap year.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    int leap_year(int y);
    
    int main(void) {
        int year;
        printf("Enter year.\n");
        scanf("%d", &year);
        if (leap_year(year) == 1)
            printf("It is a leap year.\n");
        else
            printf("It is not a leap year.\n");
        return 0;
    }
    
    int leap_year(int y) {
        if (y % 4 == 0) {
            if (y % 100 != 0 || y % 400 == 0)
                return 1;
        }
        else return 0;
    }
  12. 비만을 평가하는 기준에는 여러 가지가 있지만 보편적으로 사용하는 방법은 체질량 지수(BMI: Body Mass Index)다. 이는 몸무게를 키의 거의 제곱으로 나눈 값으로서 미국은 BMI 지수가 18.5 미만이면 저체중(Underweight)으로 분류한다. 또 18.5 이상 25.0 미만이면 정상 체중(normal), 25.0 이상이면 과체중(Overweight)예를 들어, 몸무게 74kg에 zl 1.76m인 경우 체질량 지수는 74/(1.76)²=23.8로서 정상 체중이다. 몸무게와 키를 입력받아 BMI 평가 결과를 출력하는 프로그램을 작성하라.
    > Enter your weight.
    > 73(Enter)
    > Enter your height.
    > 1.76(Enter)
    > Your BMI is 23.57. It is normal.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    void clac_BMI(float w, float h);
    
    int main(void) {
        float weight, height;
        printf("Enter your weight.\n");
        scanf("%f", &weight);
        printf("Enter your height.\n");
        scanf("%f", &height);
        clac_BMI(weight, height);
        return 0;
    }
    
    void clac_BMI(float w, float h) {
        float result = w / (h * h);
        if (result < 18.5)
            printf("Your BMI is %.1f. It is Underweight.", result);
        else if (result < 25.0)
            printf("Your BMI is %.1f. It is normal.", result);
        else
            printf("Your BMI is %.1f. It is Overweight.", result);
    }
  13. 현행 가정용 전기 요금 누진세에 의하면 월 소비량이 200Kwh 이하일 경우 기본유금 910원에 단가 93.3원이다. 또 201Kwh부터 400Kwh까지는 기본요금 1600원에 단가 187.9원이고 401Kwh 이상은 기본요금 7300원에 단가 280.6원이다 하지만 여름과 겨울에 1000Kwh를 초과하면 기본요금 7300원에 단가 709.5원이 적용된다. 이렇게 하여 요금이 계산되면 여기에 세금 13.7%(부가가치세 10%, 전력산업 기반기금 3.7%)가 추가되어 청구액이 결정된다. 전력 사용량을 입력받아 청구액을 계산하는 프로그램을 작성하라. 
    [hint] 사용량은 정수형, 요금은 double 형, 청구액은 요금에 1.137을 곱한 후 정수형으로 형 변환을 한다.
    > Enter monthly amount in Kwh.
    > 500(Enter)
    > Enter 1 if summer or winter, 0 if not.
    > 1(Enter)
    > Including tax, you pay 167821.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    double clac_tax(int usage, int weather, double tax);
    
    int main(void) {
        int usage, weather;
        double charge, tax = 13.7;
        printf("Enter monthly amount in Kwh.\n");
        scanf("%d", &usage);
        printf("Enter 1 if summer or winter, 0 if not.\n");
        scanf("%d", &weather);
        charge = clac_tax(usage, weather, tax);
        printf("Including tax, you pay %d.", (int)charge);
        return 0;
    }
    
    double clac_tax(int usage, int weather, double tax) {
        double result = 0;
        if (usage > 1000 && weather == 1) {
            result += 7300 + 709.5 * usage;
        }
        else if (usage > 400) {
            result += 7300 + 280.6 * usage;
        }
        else if (usage > 200) {
            result += 1600 + 187.9 * usage;
        }
        else {
            result += 910 + 93.3 * usage;
        }
        return result * (100 + tax) / 100;
    }
    페이지 하단의 Extra문제도 도전해보세요.
  14. 계산기 프로그램을 수정하여 프로그램이 시작하면 부동 소수 연산인지 정수 연산인지 물어본 후에 결과를 출력하는 프로그램을 작성하라.
    [hint] 부동 소수 버전의 float_calculate와 정수 버전의 int_calculate라는 두 개의 함수를 작성하고 어떤 계산을 원하는지에 따라 서로 다른 함수를 호출해야 한다..
    > Enter 1 for floating point calculation, 2 for integer calculation.
    > 2(Enter)
    > Enter an expression. For EXAMPLE, 2 + 5.
    > 23 % 4(Enter)
    > 23 % 4 = 3
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    float float_calculate(float a, float b, char op);
    
    int int_calculate(int a, int b, char op);
    
    int main(void) {
        char ch;
        int mode;
        float a, b;
        printf("Enter 1 for floating point calculation, 2 for integer calculation.\n");
        scanf("%d", &mode);
        if (mode != 1 && mode != 2) {
            printf("계산기 모드는 1 또는 2를 입력해야만 합니다. 프로그램을 종료합니다.\n");
            return -1;
        }
        printf("Enter an expression. For EXAMPLE, 2 + 5.\n");
        scanf("%f %c %f", &a, &ch, &b);
        if (mode == 1)
            printf("%f %c %f = %f", a, ch, b, float_calculate(a, b, ch));
        else
            printf("%d %c %d = %d", (int)a, ch, (int)b, int_calculate(a, b, ch));
        return 0;
    }
    
    float float_calculate(float a, float b, char op) {
        switch (op) {
        case '+':
            return a + b;
            break;
        case '-':
            return a - b;
            break;
        case '*':
            return a * b;
            break;
        case '/':
            if (b != 0) return a / b;
            else {
                printf("에러 :: 분모는 0이어선 안됩니다.\n");
                return -1;
            }
        case '%':
            if (b != 0) return (int)a % (int)b;
            else {
                printf("에러 :: 분모는 0이어선 안됩니다.\n");
                return -1;
            }
        default:
            printf("에러 연산자가 비정상적입니다. 프로그램을 종료합니다.\n");
            return -1;
        }
    }
    
    int int_calculate(int a, int b, char op) {
        switch (op) {
        case '+':
            return a + b;
            break;
        case '-':
            return a - b;
            break;
        case '*':
            return a * b;
            break;
        case '/':
            if (b != 0) return a / b;
            else {
                printf("에러 :: 분모는 0이어선 안됩니다.\n");
                return -1;
            }
        case '%':
            if (b != 0) return (int)a % (int)b;
            else {
                printf("에러 :: 분모는 0이어선 안됩니다.\n");
                return -1;
            }
        default:
            printf("에러 연산자가 비정상적입니다. 프로그램을 종료합니다.\n");
            return -1;
        }
    }
    사실 코드를 이렇게 짜면 안됩니다. int형 함수와 float함수의 코드가 출력 결과의 자료형은 다르지만 연산하는 부분의 코드가 모두 동일하기 때문입니다.
  15. 제품의 단가, 개수, 급행 여부를 물어보고 지불해야 할 운송료 총액을 계산하는 프로그램을 작성하라. 단, 금액이 20000원 이상이면 운송료는 1500원이고 그 미만이면 2000원이다. 또, 급행일 경우에는 1000원이 추가된다.
    > 단가를 입력하세요.
    > 5000(Enter) 
    > 개수를 입력하세요.
    > 6(Enter)
    > 급행 여부를 입력하세요. (1: 급행, 0: 아님)
    > 1(Enter)
    > 지불해야 할 총액은 32500원입니다.
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <stdio.h>
    
    int sumAll(int p, int c, int e);
    
    int main(void) {
        int price, cnt, express, sum = 0;
        printf("단가를 입력하세요.\n");
        scanf("%d", &price);
        printf("개수를 입력하세요.\n");
        scanf("%d", &cnt);
        printf("급행 여부를 입력하세요. (1: 급행, 0: 아님)\n");
        scanf("%d", &express);
        sum = sumAll(price, cnt, express);
        printf("지불해야 할 총액은 %d원 입니다.\n", sum);
        return 0;
    }
    
    
    int sumAll(int p, int c, int e) {
        int result = 0;
        result = p * c;
        if (result >= 20000) {
            result += 1500;
        }
        else {
            result += 2000;
        }
        if (e != 0) {
            result += 1000;
        }
        return result;
    }

Extra문제

13번 심화(실제 누진요금 계산기)

// 실제 누진세 구간별 적용하기

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

double clac_tax(int usage, int weather, double tax);

int main(void) {
    int usage, weather;
    double charge, tax = 13.7;
    printf("Enter monthly amount in Kwh.\n");
    scanf("%d", &usage);
    printf("Enter 1 if summer or winter, 0 if not.\n");
    scanf("%d", &weather);
    charge = clac_tax(usage, weather, tax);
    printf("Including tax, you pay %d.", (int)charge);
    return 0;
}

double clac_tax(int usage, int weather, double tax) {
    double result = 0;
    int temp;
    if (usage > 1000 && weather == 1) {
        temp = usage - 1000;
            result += 709.5 * temp;
        usage -= temp;
    }
    if (usage > 400) {
        temp = usage - 400;
        result += 7300 + 280.6 * temp;
        usage -= temp;
    }
    if (usage > 200) {
        temp = usage - 200;
        result += 1600 + 187.9 * temp;
        usage -= temp;
    }
    result += 910 + 93.3 * usage;
    return result * (100 + tax)/100;
}


//모든 예제 소스는 한빛 미디어홈페이지에서 찾으실 수 있습니다.

IT CookBook, 전공자를 위한 C 언어 프로그래밍 (hanbit.co.kr)

또는 cyphen156/Work-space: Studying (github.com)에서 찾으실 수 있습니다.

 

 

 

 

 

'프로그래밍 > C언어' 카테고리의 다른 글

Chapter6 과제  (0) 2023.08.07
Chapter6 반복문 : for와 while  (0) 2023.07.12
Chapter5 조건문 : If와 Switch  (0) 2023.06.02
Chapter4 과제  (0) 2023.02.10
Chapter4 함수Ⅰ  (0) 2023.02.09