我在我的代碼中遇到了一個主要問題,即當我點擊 1 并且 j 為 5 時,雖然布爾函式回傳 False,但 IF 陳述句仍然可以運行。
#include <iostream>
using namespace std;
#include <string>
using namespace std;
bool checkSym(string s, int left, int right) {
if (left >= right)
return true;
else {
if (int(s[left]) != int(s[right]))
return false;
else {
checkSym(s, left 1, right - 1);
}
}
}
int main() {
// TODO
string s, c, d;
s = "babadad";
int max = 0;
int n = s.length();
for (int i = 0; n - i >= max; i ) {
c = "";
for (int j = max; j <= n - i; j ) {
c = s.substr(i, j);
if (checkSym(c, 0, j - 1) && j > max) {
max = j;
d = c;
}
}
}
cout << d;
}
uj5u.com熱心網友回復:
代碼看起來不可讀。不過至少這個功能
bool checkSym(string s, int left, int right) {
if (left >= right)
return true;
else {
if (int(s[left]) != int(s[right]))
return false;
else {
checkSym(s, left 1, right - 1);
}
}
}
可以呼叫未定義的行為,因為它在此代碼段中不回傳任何內容
else {
checkSym(s, left 1, right - 1);
}
你需要寫
else {
return checkSym(s, left 1, right - 1);
}
也不清楚為什么對型別使用顯式轉換int
if (int(s[left]) != int(s[right]))
而不僅僅是寫
if ( s[left] != s[right])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427727.html
下一篇:對串列之間的函式求和
