2017-08-29 74 views
-2
/* to find the age of individuals according to youngest to oldest */ 

#include <stdio.h> 

int main(void) 
{ 
    int age1, age2, age3, youngest, middle, oldest; 
    { 
    printf ("Enter the age of the first individual: "); 
    scanf ("%d", &age1); 
    printf ("Enter the age of the second individual: "); 
    scanf ("%d", &age2); 
    printf ("Enter the age of the third individual: "); 
    scanf ("%d", &age3); 
    } 
    if (age1==age2==age3); 
    { 
    printf("All individuals have the same age of %d", &age1); 
    } 
    else 
    { 
    youngest = age1; 

    if (age1 > age2) 
     youngest = age2; 
    if (age2 > age3) 
     youngest = age3; 

    middle = age1; 

    if (age1 > age2) 
     middle = age2; 
    if (age2 < age3) 
     middle = age2; 

    oldest = age1; 

    if (age1 < age2) 
     oldest = age2; 
    if (age2 < age3) 
     oldest = age3; 

    printf("%d is the youngest.\n", youngest); 
    printf("%d is the middle.\n", middle); 
    printf("%d is the oldest.\n", oldest); 
    } 
    return 0; 
} 

我不斷收到第21行的錯誤,指出我有一個'其他'與前一個'如果'。這裏的任何專家都可以告訴我我哪裏出錯了?如果我要刪除'其他',顯示也有點不可思議。排序3個人的年齡

+4

表達'AGE-1 == == AGE2歲age3'不會做你的想法。它等於'(age1 == age2)== age3',這意味着您將'age1 == age2'的*布爾結果*與'age3'進行比較。 –

+1

'if(age1 == age2 == age3);' - 由於';',''''是單獨的 –

+1

回滾。如果沒有上下文的話,你就不應該改變這個問題! – Olaf

回答

8

在你的代碼

if (age1==age2==age3); 

是可怕的壞了。

兩個主要點,

  • age1==age2==age3表達式是要麼

    • 0 == age3,當age1 != age2
    • 1 == age3,當其中沒有age1 == age2

    爲y你想要。

  • ;if語句的末尾使下一個塊無條件。

在最好的情況,你可以重寫一樣

if ((age1 == age2) && (age2 == age3)) { .... } 

之後,在

printf("All individuals have the same age of %d", &age1); 

情況下,你不需要通過地址 - 變量爲。這實際上使得聲明非常錯誤,將不兼容的參數類型傳遞給提供的轉換說明符,這會導致undefined behavior

0

少IFS如果使用可變

#define swap(a,b) do { int c = (a); (a) = (b); (b) = (c);} while(0) 
if (age[2] > age[1]) swap(age[2], age[1]); 
if (age[1] > age[0]) swap(age[1], age[0]); 
if (age[2] > age[1]) swap(age[2], age[1]); 

if (age2 > age1) swap(age2, age1); 
if (age1 > age0) swap(age1, age0); 
if (age2 > age1) swap(age2, age1);