저는 C 프로그래밍 초보자이며 방금 코드에서 if-else 문을 사용하여 계산기를 작성했습니다. 그리고 switch 문을 사용하여 동일한 작업을 시도했지만 항상 기본값을 실행합니다. 내 코드를 살펴보고 잘못된 점을 제안 해주세요. 현재 CodeBlock에 코드를 작성하고 있습니다.switch 문을 사용하여 C로 간단한 계산기 만들기
int main()
{
printf("\nWhat operation do you want to do:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n");
float num1;
printf("Please enter the first number: ");
scanf("%f", &num1);
float num2;
printf("Please enter the second number: ");
scanf("%f", &num2);
char myChar;
scanf("%c", &myChar);
switch (myChar)
{
case 'A':
printf("The addition of %.2f and %.2f is %.2f", num1, num2, num1 + num2);
break;
case 'B':
printf("The subtraction of %.2f and %.2f is %.2f", num1, num2, num1 - num2);
break;
case 'C':
printf("The multiplication of %.2f and %.2f is %.2f", num1, num2, num1 * num2);
break;
case 'D':
printf("The quotient of %.2f and %.2f is %.2f", num1, num2, num1/num2);
break;
default :
printf("You enterned incorrect input");
break;
}
return 0;
}
은 어떤 도움이 귀하의 문제는 대부분 이전의 입력에서 나머지 \n
는 하나의 입력으로 해석했다 scanf
관련이
char myChar; – BLUEPIXY
'scanf ("% c", & myChar)'는 두 번째 숫자를 읽은 후 줄 바꿈을 읽고 있습니다. 'switch()'는 그 대소 문자를 가지지 않으므로 기본값을 실행합니다. – Dmitri
줄을 읽으려면 줄을 읽는 코드를 사용하고 문자 나 숫자를 읽는 코드는 사용하지 마십시오. 코드가 표시된 것처럼 작동하려면 코드에서 두 개의 숫자와 문자를 읽으므로 "32 43+"을 입력해야합니다. –