該函數使用整數數組,數組中的元素數目爲 ,並嘗試查找 數組中的多數元素。如果存在多數元素,則將其置於 *結果中,並且函數返回true。 如果不存在多數元素,則函數返回 false。在這種情況下,不應使用*結果。在C中調試函數
我的輸出對於我正在編寫的程序無法正常工作,這是因爲我覺得這個findMajority函數。
這就是輸出應該是這樣的:http://pastebin.com/Q5ycXHrg
這是我的輸出是什麼樣子:http://pastebin.com/7P1ZTpML
這是輸入:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3
1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1 1
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1
1 2 3
1 1 1
1 2 1
1 2
1 1
2
1 1 1 1 2 3 4 5 6 7
下面是函數:
int findMajority(int *array, int count, int *result){
int i, counter, bcount = 0, ccount = 0, candidate, j;
if(count == 1) {
*result = *array;
return true;
}
if(count % 2 != 0) {
for(i = 0; i < count; i++) {
if(*(array + i) == *(array + count)) {
counter++;
}
}
if(counter > (count/2)) {
*result = *(array + count);
return true;
}
else {
*(array + count) = 0;
count--;
}
}
for(j=0; j <= count; j += 2) {
if(*(array + j) == *(array + (j + 1))) {
*(array + (count + 1)) = *(array + j);
bcount++;//how many numbers on the end of the array
}
}
if(bcount == 1) {
int k = count;
while(*(array + k) == 0) {
candidate = *(array + k);
}
}
else
findMajority((array + count), count, result);
for(j=0; j <= count; j += 2) {
if(*(array + j) == candidate) {
ccount++;
}
}
if(ccount > (count/2)) {
*result = candidate;
return true;
}
else
return false;
}
我在您的「問題」中看不到問題...... – 2013-03-02 01:33:45
實際上這很清楚。我輸出的輸出與預期輸出相比是不正確的。 – 2013-03-02 01:36:45
[C程序中的錯誤輸出]的可能重複(http://stackoverflow.com/questions/15169454/incorrect-output-in-c-program)。我知道你試圖改善你的問題以符合網站要求,但我們寧願你通過編輯你的原始問題來做到這一點(使用'edit'鏈接),而不是創建一個全新的問題。 – 2013-03-02 01:42:03