ソースコードは下記のとおりなのですが、プログラムを実行すると、どんな年・月・日を入力しても「正解です。」と表示されてしまいます。
difftime関数の返却値を代入した、変数diftmの値が0になっていることが問題だと思われますが、なぜ変数diftmの値が0になるのでしょうか。ご教示いただければ幸いです。
#include <stdio.h>
#include <time.h>
int is_leap(int year);
int monthdays(int year, int month);
int main(void)
{
time_t crtt;
struct tm *crtlt;
struct tm anslt = {0};
time_t anst;
struct tm inlt = {0};
int diftm = 1;
srand(time(&crtt));
crtlt = localtime(&crtt);
anst = mktime(&anslt);
anslt.tm_year = 1 + rand() % crtlt->tm_year;
anslt.tm_mon = rand() % 12;
anslt.tm_mday = 1 + rand() % monthdays(anslt.tm_year, anslt.tm_mon);
printf("日付当てゲームを開始します。\n年月日を当ててください。\nなお、答えは1900年から現在の年までです。\n");
do {
printf("年:"); scanf("%d", &inlt.tm_year);
printf("月:"); scanf("%d", &inlt.tm_mon);
printf("日:"); scanf("%d", &inlt.tm_mday);
if (inlt.tm_mon < 1 || inlt.tm_mon > 12)
printf("入力が不正です。再入力してください。\n");
else if (inlt.tm_year < 1900 || inlt.tm_year > crtlt->tm_year + 1900)
printf("答えは1900年から現在の年までです。再入力してください。\n");
else if (inlt.tm_mday < 1 || inlt.tm_mday > monthdays(inlt.tm_year, inlt.tm_mon))
printf("入力が不正です。再入力してください。\n");
else {
time_t intm;
inlt.tm_year -= 1900;
inlt.tm_mon--;
printf("%d\n", diftm); /*デバッグ用*/
intm = mktime(&inlt);
diftm = (int)difftime(anst, intm);
printf("%d\n", diftm); /*デバッグ用*/
if (diftm > 0)
printf("それよりも後です。\n");
else if (diftm < 0)
printf("それよりも前です。\n");
}
printf("%d\n", diftm); /*デバッグ用*/
} while (diftm);
printf("正解です。\n");
return 0;
}
int is_leap(int year)
{
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
int monthdays(int year, int month)
{
int mday[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month-- != 2)
return mday[month];
return (mday[month] + is_leap(year));
}