2012-03-03

陣列元素位置的起算法(一)

這是我幫一位學生解析其程式的內容, 程式內最後 x 的值為何 ? 

#include <iostream>
using std::cout;
using std::endl;

int mystery2(const char *s);

int main( )
{
   char *string1 = "MingChi University"; //字串
   char string2[] = "Electrical Engineering";
   mystery2(&string1[2]);
   cout<< mystery2(&string2[3]) <<endl;
}

int mystery2(const char *s)
{
   static int x = 0;
   for ( ; *s != '\0' ; s++)
      x += (( *s != 'i' ) ? 1 : 0 );
   return x;
}

解析如下 :

程式中 mystery2(&string1[2]); 字串 "MingChi University" 會由第 3 個(含)算起 , 包括空白 , 於 mystery2 函式中作累計(累計的值放入 x) , 並將 "i" 省略不計 , 累計結果共 13 個字 , 接著 mystery2(&string2[3]); 字串 "Electrical Engineering" 會由第 4 個(含)算起 , 包括空白 , 同樣經過 mystery2 函式將 "i" 省略不計 , 累計共 16 個字 , 在 mystery2 函式中 x 宣告為 static , 因此執行第一次時 x 的值累計為 13 , 再執行第二次時 x 的值就從 13 開始累計 , 執行第二次完(16次) , 共累計了 13 +16 = 29 次 . 所以 x = 29 .
請注意陣列基底由0算起 .

此題目來源在以下網址 :
http://tw.knowledge.yahoo.com/question/question?qid=1607051402495

沒有留言:

張貼留言

搜尋此網誌