C++ language Write a function with the following header: int dateToNumber(int mo
ID: 663224 • Letter: C
Question
C++ language
Write a function with the following header:
int dateToNumber(int month, int day)
The purpose of this function is to convert a standard date (consisting of a day and a month) into a single number corresponding to which day of the year it is, which the function returns. For reasons that will quickly become apparently, we will start counting at 0 rather than 1. So 1/1 (January 1st) is the 0th day of the year. 12/31 (December 31st) is the 364th day of the year. 2/1 (February 1st) is the 31st day of the year (because there are 31 days in January, and we started counting at 0).
You may assume that the year is the current year (2015) and therefore there is no leap year (i.e. February has 28 days, not 29).
Explanation / Answer
#include <iostream>
using namespace std;
//prototype of method
int dateToNumber(int month, int day);
int currentYear=2015;
//test method
int main()
{
cout << "dateToNumber(12,31)=" << dateToNumber(12,31)<<endl;
return 0;
}
int dateToNumber(int month, int day)
{
int i,sum=day,temp;
//for each month
for(i=1;i<month;i++)
{
//get number of days in february
if(i==2)
{
if(currentYear%4==0)
{
temp=29;
if(currentYear%100==0 && currentYear%400!=0)
{
temp=28;
}
sum=sum+temp;
}
else
{
sum=sum+28;
}
}
//get number of days in months april,june,september,november
else if (i==4 || i==6 || i==9 ||i==11)
{
sum=sum+30;
}
//get number of days in remaining months
else
{
sum=sum+31;
}
}
return sum-1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.