當我更改傳遞給陣列的值時,我收到奇怪的錯誤,該錯誤不會停止程式,但它總是出現,所以我很好奇為什么。我在下面給你我的代碼:我的錯誤是這樣的:在函式'int numOfDifferentElements(BSTree*, int)'中:控制到達非空函式的結尾[-Wreturn-type](main.cpp:97:1)和有一個箭頭指向:}
#include <iostream>
using namespace std;
struct BSTree
{
int val;
BSTree* up;
BSTree* right;
BSTree* left;
};
void AddBstNode(BSTree* &root, int valToAdd)
{
{
BSTree* pom;
BSTree* nodeToAdd = new BSTree;
nodeToAdd->val = valToAdd;
nodeToAdd->left = NULL;
nodeToAdd->right = NULL;
nodeToAdd->up = NULL;
if (root == NULL)
{
root = nodeToAdd;
}
else
{
pom = root;
while (1)
{
if (nodeToAdd->val < pom->val)
if (pom->left == NULL)
{
pom->left = nodeToAdd;
break;
}
else
pom = pom->left;
else if(nodeToAdd->val > pom->val)
{
if (pom->right == NULL)
{
pom->right = nodeToAdd;
break;
}
else
pom = pom->right;
}
else // gdy wartosc jest rowna to jej nie dodajemy do drzewka aby potem mozna bylo zliczyc el drzewa
// a kazdy z nich bedzie inny
{
break;
}
}
nodeToAdd->up = pom;
}
}
}
int numOfDifferentElements(BSTree* root, int counter)
{
if (root)
{
counter ;
numOfDifferentElements(root->left, counter);
numOfDifferentElements(root->right, counter);
}
else
{
return counter;
}
}
void judgeArray(int array[], int x)
{
BSTree* pom = NULL;
int lengthOfArray = *(&array 1 ) - array; // rozmiar naszej tablicy
for(int i = 0; i < lengthOfArray; i )
{
AddBstNode(pom, array[i]); // tworzymy drzewo z elementow naszej tablicy
}
int counter = 0;
int judge = numOfDifferentElements(pom, counter); // zliczamy liczbe el drzewa, bez zadnych zalozen, bo
//wszystkie jego elementy sa rozne co zostalo zapewnione w funkcji AddBstNode ( kom. w linii 76 i 77)
if(judge == x)
{
cout<<"Array is good"<<endl;
}
else if(judge < x)
{
cout<<"Array is wrong"<<endl;
}
else if(judge > x)
{
cout<<"Array is mediocre"<<endl;
} // powyzej nasze zalozenia, jesli liczba roznych el jest mniejsza/wieksza/rowna od naszego zalozonego x ( liczby
//roznych elementow) to tak oceniamy nasza tablice
}
int main() {
int N[16] = {1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8}; // przykladowa tablica
int x = 12; // przykladowa wart x
judgeArray(N, x); // wywolanie naszej funkcji z przykladowa wartoscia
return 0;
}
uj5u.com熱心網友回復:
該問題是,在你的numOfDifferentElements函式,如果if條件在線北京那么有沒有return陳述句。問題是因為函式的回傳型別是非空的,所以你必須回傳一些東西。您可以通過在塊內或塊外(后)添加陳述句來解決此問題,如下所示:returnifelse
int numOfDifferentElements(BSTree* root, int counter)
{
if (root)
{
counter ;
numOfDifferentElements(root->left, counter);
numOfDifferentElements(root->right, counter);
//can also add a return statement here
}
else
{
return counter;
}
//or add return -1; or some other value indicating ERROR CODE
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377850.html
