2017-09-17 5 views
-2

저는 프로그래밍 초보자이며 두 숫자의 합 또는 곱을 제공하는 기본 계산기를 만들려고한다고 생각했습니다. 그러나이 프로그램의 while 루프에서 첫 번째 printf은 루프의 첫 번째 반복 후 두 번 인쇄됩니다. 이 문제를 해결할 수있는 도움이 있으면 대단히 감사하겠습니다.Printf는 while 루프에서 두 번 발생합니까?

#include <stdio.h> 
#include <string.h> 

int multiply(int a, int b) { 
    return a * b; 
} 

void printMultiply(int x, int y) { 
    int result = multiply(x, y); 
    printf("\n%d\n", result); 
} 

int add(int a, int b) { 
    return a + b; 
} 

void printAdd(int x, int y) { 
    int result = add(x, y); 
    printf("\n%d\n", result); 
} 

int main() { 
    int product1 = 0; 
    int product2 = 0; 

    int sum1 = 0; 
    int sum2 = 0; 

    while (true) { 
     // this prints twice after first iteration? 
     printf("Would you like to add or multiply? (press a or m)\n"); 

     char choice = ' '; 
     scanf("%c", &choice); 

     if (choice == 'm') { 
      printf("What two numbers would you like to multiply? (leave a space between numbers\n"); 
      scanf("%d%d", &product1, &product2); 
      printMultiply(product1, product2); 
     } else 
     if (choice == 'a') { 
      printf("What two numbers would you like to add? (leave a space between numbers\n"); 

      scanf("%d%d", &sum1, &sum2); 
      printAdd(sum1, sum2); 
     } 
    } 
} 
+0

아마도 당신이 알고있는 선택에 해당하지 않기 때문에 scanf에서 줄 바꿈을 눌렀을 것입니다. –

+0

'scanf (...)'가 보이지 않는 리턴 문자에 반응하고 있습니다. 'return' (_newline_) 문자를 사용하기 위해 포맷 문자열 앞에 공백 문자를 넣으십시오 :'scanf ("% c", & choice);' – ryyker

답변

3

첫 번째 반복 한 후, 당신은 scanf로 첫 번째 호출에 줄 바꿈 (\n)를보고있다.

당신이 어떤 공백을 먹고 당신의 형식 문자열에서 주도적 공간을 사용하기 만하면 :

scanf(" %c", &choice); 
+0

이해하기가 이상합니다. 나는이 문제에 아무런 문제없이 std :: cin을 사용했다. 그래서 두 개의 숫자 뒤에 'enter'를 누르면 scanf는 자동으로 다음 번에 \ n을 읽습니다. – Njgardner90

+0

예. 개행 문자를 어딘가에 소비해야합니다. 그것은'scanf'와 함께 일반적인 잡았다. – smarx

0

'\ n'을 1 회 반복 후를 ch 입력됩니다. 버퍼에서 제거하십시오.

scanf ("% d % d", & sum1, & sum2);

scanf ("% c", & enter);

0

이 시도 :

scanf("\n%c", &choice); 

이이 문제를 정렬합니다.