PTA 1028 人口普查第四个测试点答案错误
找了很久都没找到,代码如下
#include
typedef struct people{
char name[6];
int y;
int m;
int r;
}People;
int compare(People old,People young){
if(old.y < young.y){
return 1;
}else if(old.y == young.y&&old.m < old.m){
return 1;
}else if(old.y == young.y&&old.m == old.m&&old.r <= young.r){
return 1;
}
return 0;
}
int main(){
int n,i;
scanf("%d",&n);
int count=0;
People rsold,rsyoung;
People oldest={"name",1814,9,6},youngest={"name",2014,9,6};
for(i=0;itemp;
scanf("%s %d/%d/%d",temp.name,&temp.y,&temp.m,&temp.r);
if(compare(oldest,temp)&&compare(temp,youngest)){
if(!count){
rsold=temp;
rsyoung=temp;
}else if(count){
if(compare(temp,rsold)){
rsold=temp;
}
if(compare(rsyoung,temp)){
rsyoung=temp;
}
}
count++;
}
}
if(count){
printf("%d %s %s",count,rsold.name,rsyoung.name);
}else{
printf("0");
}
return 0;
}
是按照以下代码写的,以下代码答案全对,但我找不到和我的代码有什么差别
// #include
// struct Birthday {
// char name[6];
// int year;
// int month;
// int day;
// };
// int compareOld(struct Birthday a, struct Birthday b);
// //注意,有效生日数可能为0
// int main() {
// int N;
// scanf("%d", &N);
// int count = 0;
// struct Birthday oldest;
// struct Birthday youngest;
// struct Birthday today = {"name", 2014, 9, 6};
// struct Birthday early = {"name", 1814, 9, 6};
// for (int i = 0; i < N; i++) {
// struct Birthday person;
// scanf("%s %d/%d/%d", person.name, &person.year, &person.month, &person.day);
// if (compareOld(person, today) && compareOld(early, person)) {
// if (!count) {
// oldest = person;
// youngest = person;
// } else if (count) {
// if (compareOld(person, oldest)) {
// oldest = person;
// }
// if (compareOld(youngest, person)) {
// youngest = person;
// }
// }
// count++;
// }
// }
// if (count) {
// printf("%d %s %s", count, oldest.name, youngest.name);
// } else {
// printf("0");
// }
// return 0;
// }
// int compareOld(struct Birthday a, struct Birthday b) {
// if (a.year < b.year) {
// return 1;
// } else if (a.year == b.year && a.month < b.month) {
// return 1;
// } else if (a.year == b.year && a.month == b.month && a.day <= b.day) {
// return 1;
// }
// return 0;
// }
参考GPT和自己的思路:
经过对比,可以发现你的代码在第11行的条件判断语句中,将比较月份的变量写成了"old.m < old.m",应该修改为"old.m < young.m"。这个问题导致了比较结果的错误,导致输出的答案不正确。将这个错误修改之后,你的代码应该可以通过第四个测试点。
参考GPT和自己的思路:
经过分析和比较两份代码,可以发现两份代码最大的区别在于比较函数 compare
的实现上。其中你的代码实现的比较函数 compare
,在第二个 else if
和第三个 else if
中,比较的是 old.m < old.m
和 old.m == old.m && old.r <= young.r
,而实际上应该比较的是 old.m < young.m
和 old.m == young.m && old.r <= young.r
。可以看到,你的代码笔误了。而第二份代码中的比较函数 compareOld
实现是正确的,所以可以 AC。
正确的比较函数实现如下:
int compare(People old, People young) {
if (old.y < young.y) {
return 1;
} else if (old.y == young.y && old.m < young.m) {
return 1;
} else if (old.y == young.y && old.m == young.m && old.r <= young.r) {
return 1;
}
return 0;
}
参考:https://blog.csdn.net/qq_51774501/article/details/127663771