C Printf在while循环中发生两次?

C Printf在while循环中发生两次?,c,printf,C,Printf,因此,我是一个编程新手,我想我会尝试制作一个基本的计算器,给出两个数字的和或积。但是,在该程序的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

因此,我是一个编程新手,我想我会尝试制作一个基本的计算器,给出两个数字的和或积。但是,在该程序的
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);
        }
    }
}
#包括
#包括
整数乘法(整数a,整数b){
返回a*b;
}
无效打印倍增(整数x,整数y){
int结果=乘(x,y);
printf(“\n%d\n”,结果);
}
整数相加(整数a,整数b){
返回a+b;
}
无效打印添加(整数x,整数y){
int结果=相加(x,y);
printf(“\n%d\n”,结果);
}
int main(){
int product1=0;
int-product2=0;
int sum1=0;
int-sum2=0;
while(true){
//第一次迭代后打印两次?
printf(“您想加法还是乘法?(按a或m)\n”);
字符选择=“”;
scanf(“%c”,选择(&c));
如果(选项='m'){
printf(“您希望将哪两个数字相乘?(在数字之间留出空格\n”);
scanf(“%d%d”、&product1和&product2);
打印倍增(产品1、产品2);
}否则
如果(选项=='a'){
printf(“您想添加哪两个数字?(在数字之间留出空格\n”);
scanf(“%d%d”、&sum1和&sum2);
打印添加(sum1、sum2);
}
}
}

在第一次迭代之后,您在对
scanf
的第一次调用中看到一个新行(
\n

您需要做的就是在格式字符串中使用前导空格来消除任何空白:

scanf(" %c", &choice);

“\n”在第一次迭代后输入ch。 将其从缓冲区中移除

scanf(“%d%d”、&sum1和&sum2)

scanf(“%c”,&enter);

尝试以下方法:

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

这将解决您的问题。

您可能从scanf中点击了换行符,因为它不属于您已知的循环选择。
scanf(…)
正在对一个看不见的返回字符作出反应。请尝试在格式字符串前面放置一个空格字符,以使用
返回
(换行)字符:
scanf(“%c”,&choice)
这对我来说很奇怪。我使用std::cin进行这项工作时没有遇到任何问题,这让我很吃惊。所以在两个数字之后按“enter”意味着scanf会在下一轮自动读取\n?是的。你需要在某个地方使用换行符。这是
scanf
的常见问题。