C - 计算从 X 年到 Y 年的所有日期
请忽略,无能是最好的!
只是在一些嵌套的 for 循环中搞乱了一些基本文件 i/o,但输出并不完全是我想要的,尽管我似乎无法得到它工作了。
#include <stdio.h>
int main(void) {
FILE *pFile;
pFile = fopen("dates.txt", "w");
int day, month, year;
for(day = 1; day <= 31; day++) {
for(month = 1; month <= 12; month++) {
for(year = 1900; year <= 2050; year++) {
if(day < 10 && month < 10) {
fprintf(pFile, "0%d/0%d/%d\n", day, month, year);
}else {
fprintf(pFile, "%d/%d/%d\n", day, month, year);
}
}
}
}
return 0;
}
任何提示非常感谢!需要注意的是,这不是一项家庭作业,实际上只是一些实验。
干杯。
Please IGNORE, incompetence as its best!
Just messing with some basic file i/o really, in some nested for Loops but the output isn't quite what I want, though I can't seem to get it working.
#include <stdio.h>
int main(void) {
FILE *pFile;
pFile = fopen("dates.txt", "w");
int day, month, year;
for(day = 1; day <= 31; day++) {
for(month = 1; month <= 12; month++) {
for(year = 1900; year <= 2050; year++) {
if(day < 10 && month < 10) {
fprintf(pFile, "0%d/0%d/%d\n", day, month, year);
}else {
fprintf(pFile, "%d/%d/%d\n", day, month, year);
}
}
}
}
return 0;
}
Any tips much appreciated! And as a heads up, this isn't an homework task, just some experimentation really.
Cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
mktime
创建日期。然后添加 1 天并创建下一个日期。这样就可以迭代了。
以下代码显示前 200 个日期。
顺便说一句,它工作的日期晚于纪元。至少在我的
x86_64 GNU/Linux
中的gcc version 4.4.3
上是这样You can use
mktime
to create a date. Then add 1 day to it and create the next date.This way you can iterate.
Following code shows first 200 dates.
By the way it works dates behind epoch. At least on my
gcc version 4.4.3
inx86_64 GNU/Linux
实际上,您可以有 4 种日期和月份的组合,其中可以或可以不添加 0 前缀,您尝试使用单个 if else 来处理它们。
情况1:日和月都<10,由第一个if处理。
情况2:日> 10、月< 10、未处理
情况3:日<; 10、月> 10、未处理
情况4:两者均>; 10.在else中处理。
%02d 是处理所有情况的选项。
You can actually have 4 combinations of day and month in which you may or may not prefix with 0, which you are trying to handle with single if else.
Case 1: Both day and month <10, handled by first if.
Case 2: Day > 10 and Month < 10, un-handled
Case 3: Day < 10 and Month > 10, un-handled
Case 4: Both are > 10. Handled in else.
%02d is the option to handle all the cases.
您可能希望年循环在月循环之前,在日循环之前(与当前顺序相反)。
您需要使每月最大日期的测试更加聪明(您需要了解闰年的规则(请注意,1900 年不是闰年,与 MS Excel 相比,而 2000 年是)。
您可以使用
%02d
或%.2d
打印 2 位数字的月份和日期,因此您只需要一个printf()
语句。You probably want the year loop before the month loop before the day loop (the reverse of the current order).
You are going to need to make the testing for maximum day of the month cleverer (you need to know the rules for leap years (noting that 1900 was not a leap year, pace MS Excel, and 2000 was).
You can use
%02d
or%.2d
to print 2 digits for the month and day, so you only need a singleprintf()
statement.