C言語で日数を年月日形式に変換する方法

C 言語では、除算と剰余演算子を用いて日数を年月に変換できます

まず日数を365で割って年を求めます。次に余りを30で割って月を求めます。最後に余りを1で割って残りの日数を求めます。

サンプルコードを以下に示します。

#include <stdio.h>

void convertDaysToYearsMonths(int days, int *years, int *months, int *remainingDays) {
    *years = days / 365;
    *months = (days % 365) / 30;
    *remainingDays = (days % 365) % 30;
}

int main() {
    int days = 1000;
    int years, months, remainingDays;

    convertDaysToYearsMonths(days, &years, &months, &remainingDays);

    printf("%d days is equal to %d years, %d months, and %d days\n", days, years, months, remainingDays);

    return 0;
}

出力結果:

1000 days is equal to 2 years, 8 months, and 20 days

これにより、必要に応じて任意の日数を年月に変換できます。

bannerAds