所以我是编程的初学者,我想我会尝试制作一个基本计算器,给出两个数字的总和或乘积。但是,在此程序的while
循环中,第一个printf
似乎在循环的第一次迭代后打印两次。任何帮助纠正这一点将不胜感激。
#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 :(得分:3)
在第一次迭代后,您在第一次调用\n
时看到换行符(scanf
)。
您需要做的就是使用格式字符串中的前导空格来占用任何空格:
scanf(" %c", &choice);
答案 1 :(得分:0)
'\ n'进入ch。 将其从缓冲区中删除。
scanf(“%d%d”,&amp; sum1,&amp; sum2);
scanf(“%c”,&amp; enter);
答案 2 :(得分:0)
试试这个:
scanf("\n%c", &choice);
这将解决您的问题。