2013-03-17 34 views
0

我有功能,這應該算多少字符有最長的詞,但它計算錯誤。多少個字符具有最長的單詞用C

例如,如果我輸入兩個詞時,第一個比第二個短:「我的名字」節目讓我發現,最長的詞有2個字符。但是當我輸入「命名我的」時,顯示結果是4.爲什麼?

void max_chars(ListNodePtr sPtr) 
{ 
    int i = 0; 
    int max = 0; 

    while (sPtr->next != NULL) { 
     if (isalpha(sPtr->data)) { 
      i++; 
     } else { 
      if (i > max) { 
       max = i; 
      } 
      i = 0; 
     } 
     sPtr = sPtr->next; 
    } 

    printf(" \n The Longest word have : %d chars \n", max); 
} 
+0

是'特徵碼= sPtr-> next'遞增的東西嗎?我提到它是因爲你每循環調用兩次。一個在while語句中,一個在循環體中。如果它增加了一些指針,那麼你就會走兩兩個字符。嘗試打印當前評估的角色,看看發生了什麼。 – Jean 2013-03-17 22:07:19

+0

而不是使用NULL使用'\ 0'(標準) – Mitro 2013-03-17 22:21:14

+0

並看看這個http://stackoverflow.com/questions/15340343/strings-gets-and-do-while – Mitro 2013-03-17 22:22:24

回答

2

my name當你到達節點ebreak循環,因爲nextnull等等max不會被更新。
您應該更新max環路以外以及或改變循環的條件

0
void max_chars(ListNodePtr sPtr) 
{ 
    int i = 0; 
    int imax = 0; 

    for(;sPtr; sPtr = sPtr->next;) { 
     if (isalpha(sPtr->data)) { if(++i > imax) imax=i; } 
     else { i = 0; } 
    } 

    printf(" \n The Longest word have : %d chars \n", imax); 
} 
相關問題