2011-06-11 17 views
1

我寫了一個函數來搜索數組中的char,如果找到了返回它的後繼,否則返回-1。然後,如果單詞以元音結尾,算法會添加一個輔音,反之亦然。兩個條件不能以相同的方式工作,我不明白爲什麼

此代碼工作得很好,即使該文件的最後一個字:

changedChar = cipherChar(character, consonants, tConsonants); 
if (changedChar != -1) charType = 'c'; 
else { 
    changedChar = cipherChar(character, CONSONANTS, tConsonants); 
    if (changedChar != -1) charType = 'c'; 
    else { 
     changedChar = cipherChar(character, vowels, tVowels); 
     if (changedChar != -1) charType = 'v'; 
     else { 
      changedChar = cipherChar(character, VOWELS, tVowels); 
      if (changedChar != -1) charType = 'v'; 
      else { 
       changedChar = cipherChar(character, others, tOthers); 
       if (changedChar != -1) charType = 'o'; 
       else { 
        changedChar = changeDigit(character); 
        if (changedChar != -1) charType = 'o'; 
        else { 
         changedChar = cipherChar(character, punctuation, tPunctuation); 
         if (changedChar != -1) charType = 'o'; 
        } 
       } 
      } 
     } 
    } 
} 
if (changedChar != -1) outFile << changedChar; 
    if (searchChar(inFile.peek(), punctuation, tPunctuation) > -1) 
     if (charType == 'v') { 
      outFile << consonants[nVowel]; 
      nVowel < 4 ? nVowel++ : nVowel = 0; 
     } 
     else if (charType == 'c') { 
      outFile << vowels[nConsonant]; 
    nConsonant < 20 ? nConsonant++ : nConsonant = 0; 
     } 

但這其他文件的最後一個字後不增加額外的信:

charType = 'c'; 
changedChar = cipherChar(character, consonants, tConsonants); 
if (changedChar == -1) { 
    changedChar = cipherChar(character, CONSONANTS, tConsonants); 
    if (changedChar == -1) { 
     charType = 'v'; 
     changedChar = cipherChar(character, vowels, tVowels); 
     if (changedChar == -1) { 
      changedChar = cipherChar(character, VOWELS, tVowels); 
      if (changedChar == -1) { 
       charType = 'o'; 
       changedChar = cipherChar(character, others, tOthers); 
       if (changedChar == -1) { 
        changedChar = changeDigit(character); 
        if (changedChar == -1) changedChar = cipherChar(character, punctuation, tPunctuation); 
       } 
      } 
     } 
    } 
} 
if (changedChar != -1) outFile << changedChar; 
    if (searchChar(inFile.peek(), punctuation, tPunctuation) > -1) 
     if (charType == 'v') { 
      outFile << consonants[nVowel]; 
      nVowel < 4 ? nVowel++ : nVowel = 0; 
     } 
     else if (charType == 'c') { 
      outFile << vowels[nConsonant]; 
    nConsonant < 20 ? nConsonant++ : nConsonant = 0; 
     } 

爲什麼?我很困惑。

+12

看了這麼多條件後,我太困惑了。 – CharithJ 2011-06-11 00:41:55

+1

好金字塔.. – Dani 2011-06-11 01:45:15

回答

3

我看到的唯一區別在於,在第二部件的代碼如果沒有找到然後charType具有值'o',而在第一代​​碼段,如果沒有被發現,然後charType有任何它的初始值是這樣的代碼之前運行(你沒有向我們顯示)。

除此之外,這兩段代碼在語義上是相同的,所以如果這不是問題的原因,那麼問題在於你沒有向我們顯示的代碼。

6

如果在邏輯中存在這麼多的條件,那麼很可能在功能設計中存在一個缺陷。正確理解您的要求並嘗試簡化邏輯。

相關問題