c++中if语句的模行为

Modulo behaviour with if statement in C++

本文关键字:语句 if c++      更新时间:2023-10-16

为什么这段代码返回5。首先,if返回5%2 = 1,if(1)返回false。为什么呢?

#include <iostream>
using namespace std;
int fn_test(int i=5)
{
    if(i%2) return i++;
    else
    return fn_test(i-1);
}
int main()
{ int test=fn_test(5);
   cout<< " this is out put " << test;
   return 0;
}

您注意到5%2的结果是1,它是非零的,因此是"true"。只有零是"假",其他都是"真"。

这意味着你做return i++,它返回i(即5)的值,然后再增加i