반응형
1. 문법
switch (n) { case constant1: // code to be executed if n is equal to constant1; break; case constant2: // code to be executed if n is equal to constant2; break; . . . default: // code to be executed if n doesn't match any constant }
2. 소스
# include <stdio.h> int main() { char operator; double firstNumber,secondNumber; printf("Enter an operator (+, -, *,): "); scanf("%c", &operator); printf("Enter two operands: "); scanf("%lf %lf",&firstNumber, &secondNumber); switch(operator) { case '+': printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber+secondNumber); break; case '-': printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber); break; case '*': printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber*secondNumber); break; case '/': printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber); break; // operator is doesn't match any case constant (+, -, *, /) default: printf("Error! operator is not correct"); } return 0; }
반응형