2015-12-13 54 views
1

我必須在給定數組中找到第三大偶數分數。我知道分數不可能是奇數或偶數,但根據準則,即使分子也是偶數分數。我已經獲得了部分代碼的部分工作。查找給定數組中的第三大偶數分數

測試案例1:

1/2 
2/3 
2/5 
2/7 

程序將返回正確2/7第三大甚至部分。

測試案例2:

1/2 
2/3 
2/5 
2/7 
2/5 

程序返回2/5第三大時,我期待的2/7輸出。

測試案例3:

1/2 
2/3 
2/5 
2/5 
2/7 
2/7 

程序應該還是回到2/7,但它吐出回2/5

誰能給我一個提示或指出哪裏我的邏輯是錯誤的?如果這些值不重複,代碼將起作用。這是我的嘗試。

int main() { 
    Fraction largest; 
    Fraction secondlargest; 
    Fraction thirdlargest; 
    Fraction** arr; 
    int size; 

    std::cout << "How many fractions? "; 
    std::cin >> size; 

    arr = new Fraction*[size] {nullptr}; 

    for (int i = 0; i < size; i++) { 
     createFraction(&arr[i]); 
    } 

    for (int i = 0; i < size; i++) { 
     if (arr[i]->getNum() % 2 == 0) { 
      if (largest < *arr[i]) { 
       thirdlargest = secondlargest; 
       secondlargest = largest; 
       largest = *arr[i]; 
      } 
      else if (secondlargest < *arr[i]) { 
       thirdlargest = secondlargest; 
       secondlargest = *arr[i]; 
      } 
      else if (thirdlargest < *arr[i]) { 
       thirdlargest = *arr[i]; 
      } 
     } 
    } 

    std::cout << thirdlargest << " is the third largest even fraction."; 

    for (int i = 0; i < size; i++) { 
     delete arr[i]; 
    } 
    delete[] arr; 

    return 0; 
} 
+0

你有C++ 11所以爲什麼不使用vector和unique_ptr而不用擔心刪除東西? (甚至只是'std :: vector ',爲什麼每個分數都需要分配?這也會更快) –

回答

0

要看到問題的考慮會發生什麼,當輸入了相同的分數兩次:

  • 第一次將設置largest正確
  • 第二次,你會設置second_largest這不如果您不想考慮重複項,請更正

您應該更改代碼以使用模式:

if (largest < *arr[i]) { 
    thirdlargest = secondlargest; 
    secondlargest = largest; 
    largest = *arr[i]; 
} else if (largest != *arr[i]) { 
    if (secondlargest < *arr[i]) { 
     thirdlargest = secondlargest; 
     secondlargest = *arr[i]; 
    } else if (secondlargest != *arr[i]) { 
     if (thirdlargest < *arr[i]) { 
      thirdlargest = *arr[i]; 
     } 
    } 
} 
2

簡單地做一個心理一步一步的在第二和第三個例子你的代碼:

2nd example: 
1/2 -> doesn't enter the outside if. 
2/3 -> set as largest. 
2/5 -> set as second largest. 
2/7 -> set as third largest. 
2/5 -> set as third largest. 

類似的現象,在第三個例子,你不考慮重複,因此得到不正確的結果。

相關問題