排序3个人的年龄
/* to find the age of individuals according to youngest to oldest */ #include 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行得到错误,该错误表明我有一个’else’和之前的’if’。 这里的任何专家都可以告诉我哪里出错了? 如果我要删除’else’,显示也有点奇怪。
在你的代码中
if (age1==age2==age3);
是可怕的破碎。
两个要点,
-
像
age1==age2==age3
这样的表达式也是-
0 == age3
,当age1 != age2
-
1 == age3
,当age1 == age2
没有你想要的。
-
-
的
;
在if
语句的末尾使下一个块无条件。
充其量,你可以重写相同的
if ( ( age1 == age2 ) && ( age2 == age3) ) { .... }
在那之后,如果是
printf("All individuals have the same age of %d", &age1);
你不需要传递变量的地址 。 事实上,这使得语句非常错误,将不兼容的参数类型传递给提供的转换说明符,这会导致未定义的行为 。
如果你使用变量,则更少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);