正确答案:
#include<iostream>
#include<algorithm>
using namespace std;
#define N 100000
struct people{
char name[6];
int year;
int month;
int day;
}person[N];
bool ifeffitive(people a)
{
/* cout<<(a.year<2014||(a.year==2014&&a.month<9)||(a.year==2014&&a.month==9&&a.day<=6))&&\
(a.year>1814||(a.year==1814&&a.month>9)||(a.year==1814&&a.month==9&&a.day>=6));
cout<<endl;
*/
return (a.year<2014||(a.year==2014&&a.month<9)||(a.year==2014&&a.month==9&&a.day<=6))\
&&(a.year>1814||(a.year==1814&&a.month>9)||(a.year==1814&&a.month==9&&a.day>=6));
}
bool compare(people a,people b)
{
if(a.year!=b.year)
return a.year<b.year;
if(a.month!=b.month)
return a.month<b.month;
return a.day<b.day;
}
int main()
{
int n;
cin>>n;
int i;
people old,young;
old.year=2014;old.month=9;old.day=6;
young.year=1814;young.month=9;young.day=6;
int num=0;
for(i=0;i<n;i++)
{
cin>>person[i].name;
char ch;
cin>>person[i].year;
ch=getchar();
cin>>person[i].month;
ch=getchar();
cin>>person[i].day;
if(ifeffitive(person[i]))
{
num++;
if(compare(person[i],old))
old=person[i];
if(!compare(person[i],young))
young=person[i];
}
}
if(num==0)
cout<<0<<endl;
else
cout<<num<<" "<<old.name<<" "<<young.name<<endl;
return 0;
}
错误示例
#include<iostream>
#include<algorithm>
using namespace std;
#define N 100000
struct people{
char name[6];
int year;
int month;
int day;
}person[N];
bool ifeffitive(people a)
{
/* cout<<(a.year<2014||(a.year==2014&&a.month<9)||(a.year==2014&&a.month==9&&a.day<=6))&&\
(a.year>1814||(a.year==1814&&a.month>9)||(a.year==1814&&a.month==9&&a.day>=6));
cout<<endl;
*/
return (a.year<2014||(a.year==2014&&a.month<9)||(a.year==2014&&a.month==9&&a.day<=6))\
&&(a.year>1814||(a.year==1814&&a.month>9)||(a.year==1814&&a.month==9&&a.day>=6));
}
bool compare(people a,people b)
{
if(a.year!=b.year)
return a.year<b.year;
if(a.month!=b.month)
return a.month<b.month;
return a.day<b.day;
}
int main()
{
int n;
cin>>n;
int i;
int old=0,young=0;
int num=0;
for(i=0;i<n;i++)
{
cin>>person[i].name;
char ch;
cin>>person[i].year;
ch=getchar();
cin>>person[i].month;
ch=getchar();
cin>>person[i].day;
if(ifeffitive(person[i]))
{
num++;
if(compare(person[i],person[old]))
old=i;
if(!compare(person[i],person[young]))
young=i;
}
}
if(num==0)
cout<<0<<endl;
else
cout<<num<<" "<<person[old].name<<" "<<person[young].name<<endl;
return 0;
}
错误在于 int old=0,young=0
初始化年龄最大和年龄最小的人的下标为0
但是person[0]不一定是有效的,即ifeffitive==true不一定成立,所以这里不能把person[0]为初始化
注意事项:
cout<<(a.year<2014||(a.year2014&&a.month<9)||(a.year2014&&a.month9&&a.day<=6))&&
(a.year>1814||(a.year1814&&a.month>9)||(a.year1814&&a.month9&&a.day>=6));
只会输出前半部分的结果,即cout<<(a.year<2014||(a.year2014&&a.month<9)||(a.year2014&&a.month9&&a.day<=6));
如果想要输出整个判断式的结果,需要在整个判断式外加一个括号:
cout<<((a.year<2014||(a.year2014&&a.month<9)||(a.year2014&&a.month9&&a.day<=6))&&
(a.year>1814||(a.year1814&&a.month>9)||(a.year1814&&a.month==9&&a.day>=6)));