[英]Can someone explain me why is that the output, C++ recursive function
我不明白為什么在運行此代碼后
int n;
int f(int x)
{
int n;
if (x > 0)
{
if (x % 2 == 0)
{
cout << x % 10;
n = 1 + f(x / 10);
}
else
{
n = 1 + f(x / 10);
cout << x % 10;
}
return n;
}
else return 0;
}
int main()
{
cout << ' ' << f(8174);
return 0;
}
我得到4817 4
而不是48174
我需要更多的話,但我不知道該說什么:))
在 C++17 之前,未指定參數評估的順序。 這意味着編譯器可以在std::cout << ' '
之前或之后運行f(8174)
(因此它的所有std::cout <<...
語句)。
修復相當簡單,您需要將 cout 拆分為兩個語句:
int main()
{
std::cout << ' ';
std::cout << f(8174)
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.