排序3个人的年龄

时间:2017-08-29 12:45:22

标签: c if-statement

/* 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行收到错误,该错误表明我有一个&#39;其他&#39;使用之前的&#39; if&#39;。这里的任何专家都可以告诉我哪里出错了?如果我要移除其他&#39;显示器也有点奇怪。

2 个答案:

答案 0 :(得分:8)

在您的代码中

$DataSourceName = __DIR__ . "\..\Log4OM\Log4OM-Active.SQLite";
if(!file_exists($DataSourceName))
{
    $Msg = sprintf("%s does not exist", $DataSourceName);
    die($Msg);
}

非常可怕。

两个要点,

  • if (age1==age2==age3); 这样的表达式是

    • age1==age2==age30 == age3
    • age1 != age21 == age3

    没有你想要的。

  • age1 == age2语句末尾的;使下一个区块无条件。

充其量,您可以重写与

相同的内容
if

之后,如果是

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

您不需要传递变量的地址。事实上,这使得语句非常错误,将不兼容类型的参数传递给提供的转换说明符,这会导致undefined behavior

答案 1 :(得分:0)

如果使用变量

,则更少
#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);