-1
#include <stdio.h>


int multiple(int num1,int num2){
    return (num1*num2);
}

int add(int num1, int num2){
    return (num1+num2);
}
/*&x points to its value space *x points to its memory space*/
int main(){

    int num1,num2,ans;
    char func;

    printf("First number => ");
    scanf("%d",&num1);
    printf("Second number => ");
    scanf("%d",&num2);

    printf("Please Enter + for addition, or * for multiplication => ");
    scanf("%c",&func);

    if (func == '*'){
        ans = multiple(num1,num2);
    }else if(func == '+') {
        ans = add(num1,num2);
    }else {
        printf("Sorry, invalid operation");
    }

    printf("Ans : %d",ans);
    return 0;
}

当我运行我的程序时,它会提示我输入最火的数字和第二个数字,但是它不会提示我scanf("%c",&func);没有执行字符输入。

我的输出------------------------------------------------ -----------------:

$ ./p8t3 First number => 23 Second number => 32 Please Enter + for addition, or * for multiplication => Sorry, invalid operationAns : 2665616

4

2 回答 2

3

在扫描 + 或 * 运算符时,更改如下:

printf("Please Enter + for addition, or * for multiplication => ");
scanf(" %c",&func);         //use a space before '%c'
于 2013-07-13T16:06:45.053 回答
1
printf("Please Enter + for addition, or * for multiplication => ");
scanf(" %c",&func);

原因是当您输入一个数字并按 ENTER 时,scanf将处理该数字,但新行仍在输入缓冲区中。

于 2013-07-13T16:05:43.323 回答