簡體   English   中英

“並非所有控制路徑都返回值”

[英]“Not All Control Paths Return a Value”

**編輯:除了以下指出的錯誤外,按照此錯誤代碼,我還錯誤地嘗試將其編譯為Win32項目

1> MSVCRTD.lib(crtexew.obj):錯誤LNK2019:無法解析的外部符號WinMain @ 16>在函數_ _tmainCRTStartup中引用,因此避免了危機並完成了作業。 非常感謝大家的幫助。 希望當我知道一兩件事時,我可以同樣地償還社區費用。**

在本作業中,我們應該使用遞歸作為確定單詞是否符合回文資格的技術。 盡管我仍在努力適應它作為問題解決機制,但是這段代碼似乎應該可以正常工作。 但是,編譯器給我“並非所有控制路徑都返回變量”錯誤。 有任何想法嗎?

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

bool palcheck(string word, int first, int last);

int main()
{
  ofstream palindrome, NOTpalindrome;
  ifstream fin;
  string word;

  palindrome.open("palindrontest.txt");
  NOTpalindrome.open("notPalindronetest.txt");
  fin.open("input5.txt"); //list of palindromes, one per line

  if (palindrome.fail() || NOTpalindrome.fail() || fin.fail())
    return -1;

  while (fin >> word)
  {
    if (palcheck(word, 0, (word.size()-1)) == true)
      palindrome << word << endl;
    else
      NOTpalindrome << word << endl;
  }

  palindrome.close();
  NOTpalindrome.close();
  fin.close();

  return 0;
}

bool palcheck(string word, int first, int last)
{
if (first >= last)
return true;

else if (word[first] == word[last])
return palcheck(word, first+1, last-1);

else// (word[first] != word[last])
return false;

}

錯誤出在您的palcheck函數中,您忘了返回遞歸函數的值

bool palcheck(string word, int first, int last)
{
if (first == last)
return true;

else if (word[first] == word[last])
return palcheck(word, first+1, last-1); // <- this return ;)

else// ((word[first] != word[last]) || (first > last))
return false;
}

該錯誤在您的palcheck函數中。 如果else if的表達式為true,則該函數不會返回值。

以下應解決此問題:

bool palcheck(string word, int first, int last)
{
  if (first == last)
    return true;

  else if (word[first] == word[last])
    return palcheck(word, first+1, last-1);

  else// ((word[first] != word[last]) || (first > last))
    return false;
}
if (first == last)

需要是

if (first >= last)

如果有偶數個字母。

bool palcheck(string word, int first, int last)
{
if (first == last)
  return true;
else if (word[first] == word[last])
  palcheck(word, first+1, last-1); // <-here
else
  return false;

// <-reaches here
}

問題已here上面標記。 選擇這種情況時,您不會從函數返回任何內容,這是一個問題。 您可能應該使用:

  return palcheck(word, first+1, last-1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM