<分区>
我有一个函数,它以 char 数组的形式进行数学运算,返回一个 int 结果(这一切都有效,并且纯粹是为了上下文,与问题无关)。
当然,我的函数定义是:int calc(char* operation) {},它期望返回一个 int。
在解析字符串以确定操作数和要执行的操作后,我将结果分配给一个变量。我刚刚意识到我忘记将 return 语句放在函数中,但我仍然得到正确的结果......
这是函数。我最初忘记了最后一行。
// Function to return int results of operation specified in char* (argv[1])
int calc(char* operation)
{
int op_index = 0;
int end_index = 0;
for (int i = 0; i < 128; i ++)
{
if ((operation[i] < 48 || operation[i] > 57) && op_index == 0)
op_index = i;
if (operation[i] == '\0')
{
end_index = i;
i = 128;
}
}
int opa = 0;
int opb = 0;
for (int i = 0; i < op_index; i ++)
opa += (operation[i]-48)*power(10, op_index - (i+1));
for (int i = op_index+1; i < end_index; i ++)
opb += (operation[i]-48)*power(10, end_index - (i+1));
int res = 0;
if (operation[op_index] == '+')
res = opa + opb;
else if (operation[op_index] == '-')
res = opa - opb;
else if (operation[op_index] == '*')
res = opa * opb;
else if (operation[op_index] == '/')
res = opa / opb;
else if (operation[op_index] == '%')
res = opa % opb;
// This is the line that I had forgotten... but still got the right results when calling this function
return res;
}
有人对此有解释吗?我的猜测是它默认返回最后一个函数调用的结果,这是正确的,因为最终语句的 if/else 结构。
谢谢!