提问人: 提问时间:10/10/2021 最后编辑:chqrlie 更新时间:10/12/2021 访问量:116
在嵌套的 for 循环中计数未更新
Count not updating in nested for-loop
问:
我有一个程序,旨在计算星期一在特定范围内发生的天数。我在每次迭代中更新计数时遇到问题。我尝试更改计数方法,甚至将其放入一些 if 循环中,但没有效果。
当前代码
#include <stdio.h>
#define SIZE 1000
#include "printVday.h"
int main() {
//update date opposite of year so go through all the days first then the year
//while loop that checks if the date was on a Monday and gets all the Mondays from the month then checks the second last one
int d = 15, m = 5, y, day, month, year, yearplus, i = 0;
char dates[SIZE];
printf("Enter a year: ");
scanf("%d", &y);
for (year = y; year <= y + 20; year++) {
i++;
for (day = 15; day <= 24; day++) {
int dow = weekday(day, m, year);
if (dow == 1) {
printf("\n%d /%d /%d count = %d\n", day, m, year, i);
i = 0;
}
}
}
return 0;
}
int weekday(int d, int m, int y) {
return (d += m < 3 ? y-- : y - 2, 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) % 7; //Michael Keith and Tom Craver expression to minimise number of keystrokes for conversion of a gregorian date into numerical day of week. Algorithm invented by John H. Conway
}
目前我的计数正在更新,但不正确
电流输入和输出
Enter a year: 2015
18 /5 /2015 count = 1
16 /5 /2016 count = 1
23 /5 /2016 count = 0
15 /5 /2017 count = 1
22 /5 /2017 count = 0
21 /5 /2018 count = 1
20 /5 /2019 count = 1
18 /5 /2020 count = 1
17 /5 /2021 count = 1
24 /5 /2021 count = 0
...一直到2035年
期望输出
18 /5 /2015 count = 1
16 /5 /2016 count = 2
23 /5 /2016 count = 0
15 /5 /2017 count = 2
22 /5 /2017 count = 0
21 /5 /2018 count = 1
20 /5 /2019 count = 1
18 /5 /2020 count = 1
17 /5 /2021 count = 2
24 /5 /2021 count = 0
如果指定范围内只有一天恰好在星期一降落,那么它将计为 1...如果有 2 天碰巧落在指定范围内的星期一,则第一个实例将计为 2,而后者将更新为 0。
答:
0赞
chqrlie
10/10/2021
#1
您想要的输出非常具体。您希望将第一个匹配的星期一(打印该范围内的星期一总数)与随后打印 的星期一(其计数为 )区分开来。0
这是一个修改后的版本:
#include <stdio.h>
#define SIZE 1000
#include "printVday.h"
int weekday(int d, int m, int y) {
// Michael Keith and Tom Craver expression to minimise number
// of keystrokes for conversion of a Gregorian date into
// numerical day of week. Algorithm invented by John H. Conway
return (d += m < 3 ? y-- : y - 2, 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) % 7;
}
#define MONTH 5
#define START_DAY 15
#define END_DAY 24
int main() {
// while loop that checks if the date is a Monday and gets all the Mondays
// from the month then checks the second last one
int y, day, m = MONTH, year, i;
printf("Enter a year: ");
if (scanf("%d", &y) != 1)
return 1;
for (year = y; year <= y + 20; year++) {
i = 1;
for (day = START_DAY; day <= END_DAY; day++) {
int dow = weekday(day, m, year);
if (dow == 1) {
if (i != 0) {
/* on first match, add number of other Mondays in range */
i += (END_DAY - day) / 7;
}
printf("\n%d /%d /%d count = %d\n", day, m, year, i);
i = 0;
day += 6; // skip other weekdays
}
}
}
return 0;
}
评论