#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;
}
当我运行我的程序时,它会提示我进行firest和第二个数字但是它不会让我输入scanf("%c",&func);
没有被执行。
我的输出--------------------------------------------- --------------------:
$ ./p8t3
First number => 23
Second number => 32
Please Enter + for addition, or * for multiplication => Sorry, invalid operationAns : 2665616
答案 0 :(得分:3)
在扫描+或*运算符时,更改如下:
printf("Please Enter + for addition, or * for multiplication => ");
scanf(" %c",&func); //use a space before '%c'
答案 1 :(得分:1)
printf("Please Enter + for addition, or * for multiplication => ");
scanf(" %c",&func);
原因是当您输入数字并按ENTER时,scanf
将处理该数字,但新行仍在输入缓冲区中。