2012-03-25 49 views
0

以及我正在做這個功課,但我仍然沒有查看故障...當我運行(編譯後無gcc中的錯誤)似乎工作正常.. 。但是當我把輸入,即「254 34 199」的輸出返回:「有兩個相同的數字,再試一次」......根本不是邏輯。輸出仍然沒有在所有的整數值邏輯

有什麼問題?

謝謝!

#include<stdio.h> 

int main() 
{ 

    puts("Enter three numbers separated by a space to determine what is the greatest, what is the one in the middle and what is the lowest."); 

    int a, b, c; 
    scanf("%d %d %d", &a, &b, &c); 

     int imax(int a, int b) {return a < b ? b : a;} 
     int imin(int a, int b) {return a < b ? a : b;} 

    int high = imax(imax(a, b), c); 
    int low = imin(imin(a, b), c); 

    int mid(int a, int b, int c) { 
    if (a<b && a>c) return a; 
    else if (b<a && b>c) return c; 
    else return b; 
    } 

    if (high == mid && mid == low) puts("All of the numbers are equal. Try again"); 

    else if (high == mid || high == low || mid == low) puts("There's two equal numbers. Try again"); /* This else if makes me crazy cause is not logic with a lot of combinations of three numbers! */ 

    else printf("The greatest are %d, the middle are %d and the lowest are %d\n", high, mid, low); 
} 
+0

編譯?你最好打開更多的警告,然後......(gcc上的'-Wall')。不應允許在其他函數中定義函數。 – Thomas 2012-03-25 09:50:14

+1

@Thomas這是一個被濫用的gcc擴展。 – cnicutar 2012-03-25 09:51:46

+0

@Thomas,更好的辦法是添加'-std = c99'或類似的東西。 – 2012-03-25 10:51:38

回答

1

你是計算錯誤的方式,中間數,例如,如果我們把你給的值(254 34 199)在你的計算:

int mid = imax(imax(254, 34), imin(34, 199)); 

我們得到:

int mid = imax(254, 34); 

它是:

int mid = 254; 

而不是199.

+0

你能告訴我如何解決這個問題嗎? (對不起,我是C新手)。 – ignaces 2012-03-25 09:51:33

+1

@ user1178392你也是「邏輯」,「理性」和「數學」的新手。 – cnicutar 2012-03-25 09:52:23

+1

我不想毀了你所有的樂趣:)有幾種方法可以做到這一點。 – MByD 2012-03-25 09:55:02

0

該問題已被Binyamin指出。這裏有一個指向替代方案的指針,可能是更好的解決方案:bubble sort。三個整數的情況根本不需要任何循環。

+0

我沒有看到實現像冒泡排序這樣的錯誤算法.C庫有一個qsort()函數,如果需要的話。 – 2012-03-25 09:59:24

+0

泡沫排序本身並非「不好」。在三個整數上,qsort不會比冒泡排序更快,並且由於遞歸函數調用開銷可能會更慢。 – Thomas 2012-03-25 10:00:30

+0

和MP機器上有一個並行氣泡排序,具有相當好的性能。 – hochl 2012-03-25 10:39:08