我正在做一个初学C编程练习,构建一个显示菜单的简单计算器,接受用户的操作选择,接收2个操作数并显示结果。这就是我到目前为止所拥有的:
#include<stdio.h>
int main(){
int add (int a,int b) {return a+b;}
int substract (int a,int b) {return a-b;}
int multiply (int a,int b) {return a*b;}
double divide (int a,int b) {return a/b;}
int modulo (int a,int b) {return a%b;}
int num1, num2, choice;
printf ("======MENU=======\n");
printf ("1. Add\n");
printf ("2. Substract\n");
printf ("3. Multiply\n");
printf ("4. Divide\n");
printf ("5. Modulo\n");
printf ("Please, select your operation and press enter:\n");
scanf ("%d", &choice);
switch (choice){
case 1:
printf ("Please, enter the two operands separated by space and press enter:\n");
scanf ("%d %d", &num1, &num2);
add (num1, num2);
printf ("%d\n", add);
break;
case 2:
printf ("Please, enter the two operands separated by space and press enter:\n");
scanf ("%d %d", &num1, &num2);
substract (num1, num2);
printf ("%d\n", substract);
break;
case 3:
printf ("Please, enter the two operands separated by space and press enter:\n");
scanf ("%d %d", &num1, &num2);
multiply (num1, num2);
printf ("%d\n", multiply);
break;
case 4:
printf ("Please, enter the two operands separated by space and press enter:\n");
scanf ("%d %d", &num1, &num2);
divide (num1, num2);
printf ("%lf\n", divide);
break;
case 5:
printf ("Please, enter the two operands separated by space and press enter:\n");
scanf ("%d %d", &num1, &num2);
modulo (num1, num2);
printf ("%d\n", modulo);
default:
printf ("Invalid entry\n");
break;
};
scanf ("%d");
return 0;
}
我对此代码的问题是:
答案 0 :(得分:3)
TL; DR - printf ("%d\n", add);
不会打印上一个add()
函数调用的返回值,它会尝试打印函数地址本身。现在,如果对格式说明符使用了错误的参数,undefined behavior就是最终产品。
详细说明,主要问题是方法。正如你所写的那样
add (num1, num2);
printf ("%d\n", add);
这不会添加 num1
和num2
并且会神奇地打印添加的结果。你需要
收集变量中函数的返回值,然后打印该变量。
int res = -1;
res = add (num1, num2);
printf ("%d\n", res);
否则,您必须将add()
函数本身作为printf()
格式字符串中格式说明符的参数调用,如
printf ("%d\n", add (num1, num2););
同样适用于所有case
s中的其他函数调用。
另外,正如之前{{3}}中Mr. Bathseba所述,虽然您在分区函数中使用返回类型为double
,但实际的分割涉及操作数键入int
,这使得除法作为整数除法执行,然后结果将提升为double
,这可能是您不想要的。你必须强制执行浮点除法。
最后,关于嵌套函数的使用,这不是一个好主意,因为这不是标准C
。请comment。
答案 1 :(得分:1)
您正在打印功能地址:
modulo (num1, num2);
printf ("%d\n", modulo);
您必须替换为:
int var = modulo(num1, num2);
printf ("%d\n", var);