2017-01-22 3 views
-1

저는 C 프로그래밍 초보자이며 방금 코드에서 if-else 문을 사용하여 계산기를 작성했습니다. 그리고 switch 문을 사용하여 동일한 작업을 시도했지만 항상 기본값을 실행합니다. 내 코드를 살펴보고 잘못된 점을 제안 해주세요. 현재 CodeBlock에 코드를 작성하고 있습니다.switch 문을 사용하여 C로 간단한 계산기 만들기

This is the message i'm getting

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 관련이

+0

char myChar; – BLUEPIXY

+0

'scanf ("% c", & myChar)'는 두 번째 숫자를 읽은 후 줄 바꿈을 읽고 있습니다. 'switch()'는 그 대소 문자를 가지지 않으므로 기본값을 실행합니다. – Dmitri

+0

줄을 읽으려면 줄을 읽는 코드를 사용하고 문자 나 숫자를 읽는 코드는 사용하지 마십시오. 코드가 표시된 것처럼 작동하려면 코드에서 두 개의 숫자와 문자를 읽으므로 "32 43+ "을 입력해야합니다. –

답변

0

이해할 수있을 것이다.

또한 입력하라는 메시지가 해당 입력과 일치하지 않습니다.

는 수정 제안 :

float num1; 
printf("Please enter the first number: "); 
scanf("%f", &num1); 

float num2; 
printf("Please enter the second number: "); 
scanf("%f", &num2); 

printf("\nWhat operation do you want to do:\n\tA)Addition\n\tB)Subtraction\n\tC)Multiplication\n\tD)Division\n"); 
char myChar; 
scanf(" %c", &myChar); 

당신은 목적을 디버깅로 printf을 추가 할 수 있습니다 -도 도움이 될 것이다. 첫 번째 입력의 예 :

float num1; 
printf("Please enter the first number: "); 
scanf(" %f", &num1); 
printf("num1 = %f\n", num1); 
+1

' ""'중복이''% f "'이전에 중복되었습니다. – melpomene

+0

@melpomene 내 나쁜 "% f"는 공백을 건너 뜁니다. – artm