#include <iostream>
using namespace std;
int func( int a[ ] )
{
for (int i = 0; i < 16; i++) a[i] = i + 1;
a[16] = 0;
int test = 0, head;
while( test != a[test] )
{
for (int i = 1; i < 3; i++)
{
head = test;
test = a[test];
}
a[head] = a[test];
test = a[head];
}
return test;
}
int main( )
{
int arr[17];
cout << func( arr ) << endl;
system("pause"); return 0;
}
為何結果是10?想了一天了沒有想明白,求各位大神解答其中的原理,解釋幾個關鍵步驟的含義,具體簡單一點,謝謝了
uj5u.com熱心網友回復:
撈一下,求解答!!uj5u.com熱心網友回復:
a[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,0}test=0,a[test]=1
第一次while
第一次for
head=0
test=1
第二次for
head=1
test=2
a[head]=a[test]==>a[1]=a[2]==3
test=a[head]=a[1]=3
第二次while
第一次for
head=3
test=4
第二次for
head=4
test=5
a[head]=a[test]==>a[4]=a[5]==6
test=a[head]=a[4]=6
第三次while
第一次for
head=6
test=7
第二次for
head=7
test=8
a[head]=a[test]==>a[7]=a[8]==9
test=a[head]=a[7]=9
本來想一步步給你推演說明的,后來發現這樣推演太多,干脆用程式列印出來,你自己看看中途列印結果吧
int func( int a[ ] )
{
for (int i = 0; i < 16; i++) a[i] = i + 1;
a[16] = 0;
int test = 0, head;
while( test != a[test] )
{
for (int i = 1; i < 3; i++)
{
head = test;
test = a[test];
}
a[head] = a[test];
test = a[head];
printf("head=%d, test=%d, a[test]=%d\n", head, test, a[test]); //中途結果列印,以后遇到類似的問題不清楚,自己列印中途結果就知道了
}
return test;
}
int main( )
{
int arr[17];
cout << func( arr ) << endl;
system("pause"); return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/223345.html
標籤:C++ 語言
上一篇:求助 為什么報錯了
下一篇:求大佬幫忙
