/* 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 ) && ( age2 == age3) ){
printf("All individuals have the same age of %d", &age2);
}
else (age1 != age2) && (age1 != age3) && (age2 != age3);{
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;
}
您好我改变了我的代码,但是当我为每个人输入相同的年龄时,显示屏仍会显示一个奇怪的数字。我怎么做到这样,如果每个人都有相同的年龄,那么只有说所有人都具有相同年龄___的线。请帮我这个作为分级任务,我有这个
的问题所有年龄相同的人都是63567321,是最年轻的。 1是中间。 1是最老的。
答案 0 :(得分:2)
三个主要问题:
printf()
else
声明没有`if&#39; 正确代码:
/* 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 ) && ( age2 == age3) )
{
printf("All individuals have the same age of %d", age2);
}
else if ((age1 != age2) && (age1 != age3) && (age2 != age3))
{
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;
}
- 编辑
请注意,在上述解决方案中,如果其中两个年龄相等,则不会打印最旧和最年轻的年龄。要解决这个问题,我会删除else
的if条件,并在打印中间值之前包含一个检查。新的其他声明:
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);
// If two ages are equivalent, do not print middle
if ((age1 != age2) && (age1 != age3) && (age2 != age3))
printf("%d is the middle.\n", middle);
printf("%d is the oldest.\n", oldest);
}
免责声明:虽然我已经提供了上述解决方案来保留原始代码,但我希望通过以下方式采用更通用的方法:
sort(int *array, int size)
int ages[3]
sort(ages, 3);
ages[0]
,ages[1]
,ages[2]
这样代码更具可读性和可重用性。
答案 1 :(得分:0)
你为什么不做像
这样的事情{{1}}