Write a program that prints the day number of the year, given the date in the fo
ID: 3640963 • Letter: W
Question
Write a program that prints the day number of the year, given the date in the form month-day-year. For example, if the input is 1-1-2006, the day number is 1; if the input is 12-25-2006, the day number is 359. The program should check for a leap year. A year is a leap year if it is divisible by 4, but not divisible by 100. For example, 1992 and 2008 are divisible by 4, but not by 100. A year that is divisible by 100 is a leap year if it is also divisible by 400. For example, 1600 and 2000 are divisible by 400. However, 1800 is not a leap year because 1800 is not divisible by 400.Please check your program before posting, if the program works when I run it's an automatic lifesaver. Thanks a Bunch!!
I am needing this for my C++ class using visual studio.
Explanation / Answer
#include <iostream>
using namespace std;
//PROTOTYPES
void getDate(int &month, int &day, int &year);
int dayOfYear(int month, int day, int year);
int main()
{
//LOCAL DECLARATIONS
int day, month, year;
getDate(month, day, year);
cout << "Day of year: " << dayOfYear(month, day, year) << endl;
cin.sync();
cin.get();
return 0;
}
//---------------------------------------------------------
// FUNCTION DEFINITIONS
//---------------------------------------------------------
// Please enter the correct format: (month before day) and
//(month, day, year are separated by a dash (-))
//or this function will not read the correct values
//of day, month, year.
void getDate(int &month, int &day, int &year)
{
char dateStr[20];
cout << "Please enter the correct format: (m-d-y) "
<< " Month before day "
<< " Month, day, year are separated by a dash (-) "
<< " And make sure that this is a valid date ";
cout << "Enter date: ";
cin >> dateStr;
month = atoi(dateStr);
day = atoi(strstr(dateStr, "-") + 1);
year = atoi(strstr(strstr(dateStr, "-") + 1, "-") + 1);
}
//---------------------------------------------------------
int daysBeforeMonth(int m)
{
return 30 * (m - 1)+ m / 8 * 4 + ((m - 1) % 7 + 1) / 2
- 2 * (m > 2);
}
//---------------------------------------------------------
bool isLeap(int y)
{
return (!(y % 4) && y % 100) || !(y % 400);
}
//---------------------------------------------------------
int dayOfYear(int month, int day, int year)
{
return daysBeforeMonth(month)
+ (month > 2 ? isLeap(year) : 0)
+ day;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.