четверг, 7 октября 2010 г.

Определение дня недели по заданной дате

Для хранения информации о количестве дней в месяце используется константный массив. Написана функция, определяющая, является ли год високосным.
#include <iostream>
#include <algorithm>

using std::cout;
using std::cin;
using std::endl;
using std::min;
using std::max;

bool IsLeapYear(const int year) {
  if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
    return true;
  } else {
    return false;
  }
}

const int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int DefineWeekday(const int number, const int month, const int year) {
  // Reference date is 1 Jan 1990 and it is monday.
  int smaller_year = min(1990, year), bigger_year = max(1990, year);
  int days_difference = 0;
  // Count the day of the the 1 Jan of needed year.
  for (int i = smaller_year; i < bigger_year; ++i) {
    if (year > 1990) {
      days_difference += 365;
      if (IsLeapYear(i)) {
        ++days_difference;
      }
    } else {
      days_difference -= 365;
      if (IsLeapYear(i)) {
        --days_difference;
      }
    }
  }
  // Count difference between 1 Jan and our date.
  for (int i = 0; i < month - 1; ++i) {
    days_difference += days_in_month[i];
    if (i == 1 && IsLeapYear(year)) {
      ++days_difference;
    }
  }
  days_difference += number - 1;
  if (days_difference < 0) {
    return (7 + (days_difference % 7)) % 7 + 1;
  } else {
    return (days_difference % 7) + 1;
  }
}
    
  

void ReadInput(int &number, int &month, int &year) {
  cout << "Enter the number of day in month:";
  cin >> number;
  cout << "Enter the number of month:";
  cin >> month;
  if (month < 1 || month > 12) {
    cout << "Wrong number of month" << endl;
  }
  cout << "Enter the number of year:";
  cin >> year;
  if (number < 1 || number > days_in_month[ month - 1]) {
    if (month == 2 && IsLeapYear(year))
      if (number == 29) {
 return;
      }
    cout << "Wrong number" << endl;
  }
}

void WriteOutput(const int number_of_day) {
  switch(number_of_day) {
    case 1: {
      cout << "It is Monday" << endl;
      break;
    }
    case 2: {
      cout << "It is Tuesday" << endl;
      break;
    }
    case 3: {
      cout << "It is Wednesday" << endl;
      break;
    }
    case 4: {
      cout << "It is Thursday" << endl;
      break;
    }
    case 5: {
      cout << "It is Friday" << endl;
      break;
    }
    case 6: {
      cout << "It is Saturday" << endl;
      break;
    }
    case 7: {
      cout << "It is Sunday" << endl;
      break;
    }
  }
}

int main() {
  int number, month, year, day;
  ReadInput(number, month, year);
  day = DefineWeekday(number, month, year);
  WriteOutput(day);
  return 0;
}

Комментариев нет:

Отправить комментарий