C++ 1028 人口普查(20 分)

这篇博客探讨了C++解决人口普查问题的关键点,包括处理无最大或最小年龄的情况以及正确理解年龄与年份的关系。文中提到了两种方法,并指出在实现过程中容易犯的错误。

此题关键点有两处:

1  有一种情况  没有最大最小年龄的人,所以只输出0

2  判断的时候  年份越大 是越年轻   判断的时候应该注意(当时自己写写反了,思维定式)

if((temp.yy<max.yy)||((temp.yy==max.yy)&&(temp.mm<max.mm))||((temp.yy==max.yy)&&(temp.mm==max.mm)&&(temp.dd<max.dd))) max=temp;
if((temp.yy>min.yy)||((temp.yy==min.yy)&&(temp.mm>min.mm))||((temp.yy==min.yy)&&(temp.mm==min.mm)&&(temp.dd>min.dd))) min=temp;

 

方法1

#include<iostream>
using namespace std;

int main()
{   
    int n,cnt=0;
    scanf("%d",&n);
    struct birth{
        char name[6];
        int y;
        int m;
        int d;
    }a,max,min;

    max.y=2014;max.m=9;max.d=7;
    min.y=1814;max.m=9;max.d=5; 
    for(int i = 0;i<n;i++){
        scanf("%s %d/%d/%d",&a.name,&a.y,&a.m,&a.d);
        cnt++;
        if(a.y>2014||(a.y==2014&&a.m>9)||(a.y==2014&&a.m==9&&a.d>6)||a.y<1814||(a.y==1814&&a.m<9)||(a.y==1814&&a.m==9&&a.d<6)){
            cnt--;
            continue;
        }
        if(a.y<max.y||(a.y==max.y&&a.m<max.m)||(a.y==max.y&&a.m==max.m&&a.d<max.d)){
            max=a;
        }
        if(a.y>min.y||(a.y==min.y&&a.m>min.m)||(a.y==min.y&&a.m==min.m&&a.d>min.d)){
            min=a;
        }
    }
    printf("%d",cnt);
    if(cnt!=0){
        printf(" %s %s",max.name,min.name);
    }

    return 0;
}

方法2  :自写,思想都差不多

#include<iostream>
using namespace std;


int main()
{
  struct stu{
  char name[6];
  int yy;
  int mm;
  int dd;
};

  int n;
  int k=0,cnt=0;
  cin>>n;
  stu temp,max,min;
  

  
  
  for(int i=0;i<n;i++){
    scanf("%s %d/%d/%d",&temp.name,&temp.yy,&temp.mm,&temp.dd);
    if((temp.yy>2014)||((temp.yy==2014)&&(temp.mm>9))||((temp.yy==2014)&&(temp.mm==9)&&(temp.dd>6))||(temp.yy<1814) ||((temp.yy==1814)&&(temp.mm<9))||((temp.yy==1814)&&(temp.mm==9)&&(temp.dd<6))) continue;
    else{
      min=temp;
      max=temp;
      k=i+1;
      cnt ++;
      break;
    }
  }
  
  for(int i=k;i<n;i++){
    scanf("%s %d/%d/%d",&temp.name,&temp.yy,&temp.mm,&temp.dd);
    if((temp.yy>2014)||((temp.yy==2014)&&(temp.mm>9))||((temp.yy==2014)&&(temp.mm==9)&&(temp.dd>6))||(temp.yy<1814) ||((temp.yy==1814)&&(temp.mm<9))||((temp.yy==1814)&&(temp.mm==9)&&(temp.dd<6))) continue;
    else{
      cnt ++;
      if((temp.yy<max.yy)||((temp.yy==max.yy)&&(temp.mm<max.mm))||((temp.yy==max.yy)&&(temp.mm==max.mm)&&(temp.dd<max.dd))) max=temp;
      if((temp.yy>min.yy)||((temp.yy==min.yy)&&(temp.mm>min.mm))||((temp.yy==min.yy)&&(temp.mm==min.mm)&&(temp.dd>min.dd))) min=temp;
    }
  }
  
  
    cout << cnt;
    if (cnt != 0)
        cout << " " << max.name << " " << min.name;
  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值