【发布时间】:2020-12-25 18:36:10
【问题描述】:
我的任务是检查小组中的一名学生是否比另一名学生大 100 天。学生人数上限为 1000 人。计算时应考虑闰年和月份天数等其他特征。我不知道为什么我的代码不起作用。如果我输入了错误的日期(2000 年 32 月 33 日),我会出现“输入错误”的无限循环。如果日期正确,则代码不会打印即使相差100天也可以。我是初学者,希望能帮到你。
#include <stdio.h>
int main() {
int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int daysleap[13]={0,31,29,31,30,31,30,31,31,30,31,30,31};
int s, month, year, day, i, j = 0, totaldays, a[1000];
do {
printf("Number of students: ");
scanf("%d", & s);
if (s < 1 || s > 100)
printf("Incorrect input");
} while (s < 1 || s > 1000);
for (i = 0; i < s; i++) {
scanf("%d,%d,%d", & day, & month, & year);
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
if (day < 1 || day > daysleap[month]) {
printf("Incorrect input");
i = i - 1;
continue;
} else if (month < 1 || month > 12) {
printf("Incorrect input");
i = i - 1;
continue;
} else {
for (i = 1; i < year; i++) {
totaldays = 0;
totaldays += 366;
}
for (i = 1; i < month; i++)
totaldays += daysleap[i];
totaldays += day;
a[j] = totaldays;
j++;
}
} else {
if (day < 1 || day > days[month]) {
printf("Incorrect input");
i = i - 1;
continue;
} else if (month < 1 || month > 12) {
printf("Incorrect input");
i = i - 1;
continue;
} else {
for (i = 1; i < year; i++) {
totaldays = 0;
totaldays += 365;
}
for (i = 1; i < month; i++)
totaldays += days[i];
totaldays += day;
a[j] = totaldays;
j++;
}
}
}
for (i = 0; i < s; i++) {
for (j = i; j < s; j++) {
while (i < s && j < s) {
if (i != j && (a[j] - a[i] == 100))
printf("Student %d is 100 days older from Student %d", j + 1, i + 1);
if (i != j && (a[j] - a[i] == -100))
printf("Student %d is 100 days older from Student %d", i + 1, j + 1);
}
}
}
}
【问题讨论】:
-
请在发布前正确缩进您的代码。这是勉强可读的。并提供一个失败的测试用例,说明实际和预期的行为。
-
我希望这没问题。 @klutt
-
@Michael 更好,但远非好。为你修好了。
-
但是你真的应该学会调试。这可能会有所帮助:github.com/klutt/debug-small-c-programs