본문 바로가기
C and C++/C and C++ Examples

[C Examples] C 예제코드: 사칙연산 계산기 만들기, switch()

by Henry Cho 2023. 4. 14.
728x90

C 예제코드: 사칙연산 계산기 만들기, switch()

포스트 난이도: HOO_Junior


# Example Codes

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

int main()
{
    int num1,num2;
    float result;
    char ch;

    printf("Enter first number: ");
    scanf("%d",&num1);
    printf("Enter second number: ");
    scanf("%d",&num2);
    printf("Choose operation to perform (+,-,*,/,%): ");
    scanf(" %c", &ch);
    printf("You typed %c operator. \n", ch);

    switch(ch)
    {
        case '+': result=num1+num2;
            break;

        case '-': result=num1-num2;
            break;

        case '*': result=num1*num2;
            break;

        case '/': result=(float)num1/(float)num2;
            break;

        case '%': result=num1%num2;
            break;

        default:
            printf("Invalid operation.\n");
    }

    printf("Result: %d %c %d = %f\n",num1,ch,num2,result);

    return 0;
}

 


# Results

 

Enter first number: 25
Enter second number: 26
Choose operation to perform (+,-,*,/,%): +
You typed + operator. 
Result: 25 + 26 = 51.000000

# Results

 

Enter first number: 66
Enter second number: 156
Choose operation to perform (+,-,*,/,%): *
You typed * operator. 
Result: 66 * 156 = 10296.000000

 

728x90

댓글