1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

カレンダー表示

Last updated at Posted at 2018-11-26

C言語でカレンダーを表示する課題

calender.c
# include<stdio.h> // 標準入出力用

// プロトタイプ宣言
int judge_leap(int y);
int judge_week(int y, int m, int d);
void show(int leap, int weeknum, int m);

// メイン関数
int main(void) {
  int y, m, d; // 年:y, 月:m, 日:d
  int leap, weeknum; // judge_*の結果を入れる


  // 入力
  printf("年を入力してください : ");
  scanf("%d", &y);
  printf("月を入力してください : ");
  scanf("%d", &m);
  d = 1;

  // うるう年:1, 違う:0
  leap = judge_leap(y);

  // 日:0, 月:1, 火:2, 水:3, 木:4, 金:5, 土:6
  weeknum = judge_week(y, m, d);

  // 表示
  show(leap, weeknum, m);

  return 0;
}


// うるう年の判定
int judge_leap(int y) {
  if(y%4 == 0) {
    if(y%100 == 0) {
      if(y%400 == 0) {
        return 1;
      } else {
        return 0;
      }
    } else {
      return 1;
    }
  } else {
    return 0;
  }
}

// ついたちが何曜日か?の判定
int judge_week(int y, int m, int d) {
  int tmp1, tmp2; // 一時的な変数

  // 1月は13月、2月は14月として、計算する
  if(m == 1)
    m = 13;
  else if(m == 2)
    m = 14;

  // ツェラーの公式より
  tmp1 = y + y/4;
  tmp1 = tmp1 - y/100;
  tmp1 = tmp1 + y/400;
  tmp2 = (m*13 + 8)/5;

  return (tmp1 + tmp2 + d)%7;
}

// 表示
void show(leap, weeknum, m) {
  int i, j; // カウンタ
  int days[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 1月から12月の日数

  printf("日 月 火 水 木 金 土\n");
  printf("--------------------\n");

  for(i=0;i<days[m-1];i++) {
    // ついたちを表示する前にスペースを入れて形成する
    if(i == 0) {
      for(j=0;j<weeknum;j++) {
        printf("   ");
      }
    }

    // 日付を表示
    printf("%d ", i+1);
    // 1~9の数字の時、スペースを入れて形成する
    if(i+1 < 10)
      printf(" ");

    // 改行を入れて形成
    weeknum++;
    if(weeknum%7 == 0) {
      printf("\n");
    }
  }
  // 改行を入れて形成
  printf("\n");
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?