저는 프로그래밍 초보자이며 두 숫자의 합 또는 곱을 제공하는 기본 계산기를 만들려고한다고 생각했습니다. 그러나이 프로그램의 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);
}
}
}
아마도 당신이 알고있는 선택에 해당하지 않기 때문에 scanf에서 줄 바꿈을 눌렀을 것입니다. –
'scanf (...)'가 보이지 않는 리턴 문자에 반응하고 있습니다. 'return' (_newline_) 문자를 사용하기 위해 포맷 문자열 앞에 공백 문자를 넣으십시오 :'scanf ("% c", & choice);' – ryyker