#include <stdio.h> #include <string.h> int main() { int N = 0; scanf("%d", &N); char name[6]; char birth[11]; char old_name[6], young_name[6]; char old_birth1[11] = "1814/09/06", young_birth1[11] = "2014/09/06"; char old_birth2[11] = "1814/09/06", young_birth2[11] = "2014/09/06"; int count = 0; while(N) { scanf("%s %s", name, birth); if(strcmp(old_birth1, birth) <= 0 && strcmp(young_birth1, birth) >= 0) { count++; if(strcmp(old_birth2, birth) > 0) { strcpy(old_name, name); strcpy(old_birth2, birth); } if(strcmp(young_birth2, birth) < 0) { strcpy(young_name, name); strcpy(young_birth2, birth); } } N--; } printf("%d", count); if(count > 0) { printf(" %s %s\n", old_name, young_name); } return 0; }这段代码运行有误
时间: 2023-11-28 08:50:03 浏览: 87
这段代码的问题可能在于输入的人数 N 不一定大于零,但是程序却没有判断这种情况。如果 N 小于等于零,那么程序会直接输出 count,而 old_name 和 young_name 变量的值都是未定义的,这可能导致程序崩溃或输出错误的结果。为了解决这个问题,可以在程序开始时添加一个判断,如果 N 小于等于零,就直接输出 0。具体的代码修改如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
int N = 0;
scanf("%d", &N);
if (N <= 0) {
printf("0");
return 0;
}
char name[6];
char birth[11];
char old_name[6], young_name[6];
char old_birth1[11] = "1814/09/06", young_birth1[11] = "2014/09/06";
char old_birth2[11] = "1814/09/06", young_birth2[11] = "2014/09/06";
int count = 0;
while(N) {
scanf("%s %s", name, birth);
if(strcmp(old_birth1, birth) <= 0 && strcmp(young_birth1, birth) >= 0) {
count++;
if(strcmp(old_birth2, birth) > 0) {
strcpy(old_name, name);
strcpy(old_birth2, birth);
}
if(strcmp(young_birth2, birth) < 0) {
strcpy(young_name, name);
strcpy(young_birth2, birth);
}
}
N--;
}
printf("%d", count);
if(count > 0) {
printf(" %s %s\n", old_name, young_name);
}
return 0;
}
```
阅读全文