Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
#include <stdio.h>
int leapyear(int year)
{
if((year % 4 != 0) && (year % 400 != 0) || (year % 100 == 0))
{
printf("Year %d is not leap year.\n", year);
return 0;
}
else
{
printf("Year %d is leap year.\n", year);
return 1;
}
}
int addDate(int month, int date)
{
int i, febDate = 0, sum = 0, year;
if(leapyear(year) == 1)
{
febDate += 29;
}
else
{
febDate += 28;
}
for(i = 1; i < month; i++)
{
if((i <= 7) && (i != 2) && (i % 2 == 0))
{
sum += 30;
}
else if(i == 2)
{
sum += febDate;
}
else if((i >= 8) && (i % 2 != 0))
{
sum += 30;
}
else
{
sum += 31;
}
}
return sum + date;
}
int main(void)
{
int month, date, year;
printf("Enter Month: ");
scanf("%d", &month);
printf("Enter Date: ");
scanf("%d", &date);
printf("Enter Year: ");
scanf("%d", &year);
leapyear(year);
printf("%d days from Jan 1st to %d %d.\n", addDate(month, date), month, date);
return 0;
}
When I put in 8 22, 2016, I get the following:
Enter Month: 8
Enter Date: 22
Enter Year: 2016
Year 2016 is leap year.
Year -1249813628 is leap year.
235 days from Jan 1st to 8 22.
Everything looks okay except for that "Year -1249813628 is leap year." part.
What could be causing this? I tried having the main function at the very top but didn't fix the problem.
In the addDate function you call leapyear again, but now with the uninitialized local variable year.
Uninitialized local variables will have an indeterminate value (think of it as garbage). In C++ using indeterminate values will lead to undefined behavior.
You should pass year as an argument to the function instead.
int addDate(int year, int month, int date)
Related
I'm a novice in coding...
I've written a code in C++ to calculate the date after adding new numbers to date, month, and year. However, it's become too long and my computer can't process it if the date goes over 50.
Could you give me a few tips if there was a way to shorten this?
#include <iostream>
class Date{
int year; int month; int day;
}
public:
void set_date(int _year, int _month, int _day){
year=_year;
month=_month;
day=_day;
}
void add_day(int inc){
day+=inc;
}
void add_month(int inc){
month+=inc;
}
void add_year(int inc){
year+=inc;
}
void get_date(){
while (day>31){
if ((year%4)==0 && month==2 && day > 29){
month+=1;day-=29;
}
else if(month==2 && day > 28){
month+=1;day-=28;
}
else if((day>30)&&(month==4||month==6||month==9||month==11)){
month+=1;day-=30;
}
else if((day>31)&&(month==3||month==5||month==7||month==8||month==10||month==12||month==1)){
month+=1;day-=31;
}
}
if (month>12){
year+=month/12;
month=month%12;
}
std::cout<<"year"<<year<<std::endl;
std::cout<<"month"<<month<<std::endl;
std::cout<<"day"<<day<<std::endl;
}
int main(){
Date date;
date.set_data(191,2,10);
date.add_day(60);
date.add_month(10);
date.add_year(3);
date.get_date();
return 0;
}
When I run your code it loops forever with day=39 and month=13, which is a condition you don't check for. You might want to move the whole if (month>12) into your loop, so that the months get corrected while processing the days. You also want to add an else that stops the loop:
bool doneProcessing = false;
do
{
if ((year % 4) == 0 && month == 2 && day > 29)
{
month += 1;
day -= 29;
}
else if (month == 2 && day > 28)
{
month += 1;
day -= 28;
}
else if ((day > 30) && (month == 4 || month == 6 || month == 9 || month == 11))
{
month += 1;
day -= 30;
}
else if ((day > 31) && (month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 || month == 1))
{
month += 1;
day -= 31;
}
else
{
doneProcessing = true;
}
if (month > 12)
{
year += month / 12;
month = month % 12;
}
}
while (!doneProcessing);
I didn't check the validity of your semantics, but I did notice one thing: When you have month=2 and day=30, you'd want to process that as well, but you only check day>31, thus I changed the loop to simply run until the else is hit (all days are valid now).
With this change your code properly terminates after printing this result:
year195
month2
day8
PS: With a debugger you can easily and quickly find such issues. See What is a debugger and how can it help me diagnose problems?
Going through Project Euler and working through what I thought was a simple problem. For some reason when passing a struct Date by reference it results in garbage values when I try to reference or assign them. Any ideas?
#include <iostream>
using namespace std;
bool isLeapYear(int year)
{
// century
if ((year % 100 == 0) && (year % 400 == 0))
return true;
// not a century
else if ((year % 100 != 0) && (year % 4 == 0))
return true;
return false;
}
enum Months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
struct Date
{
int year;
Months month;
int day;
};
int calculateNumberOfDays(const Date& begin, const Date& end)
{
int numberOfDays = 0;
//PROBLEM: This loop never runs... Upon running it through the debugger
// the value of year is garbage i.e. -859382918
// This results in the loop not being entered and the value
// (numberOfDays) being returned as 0
for (int year = begin.year; year < end.year; year++)
{
if (isLeapYear(year))
numberOfDays += 366;
else
numberOfDays += 365;
}
//TODO: Finish for final year
return numberOfDays;
}
int main()
{
int numberOfDays = 0;
int year = 1900;
Months month = JAN;
int day = 1;
Date begin = { 1990, JAN, 1 };
Date end = { 1901, DEC, 31 };
cout << calculateNumberOfDays(begin, end) << endl;
return 0;
}
You begin date is after your end date, so the loop doesn't run. Swapping the two dates causes the loop to run correctly.
Your debugger is likely getting confused because you have two variables called year. That sent you down the wrong path.
And yes this is an assignment-- So please don't post solutions, but detailed pseudocodes are extremely helpful!
I already have a program in C++ that accepts a date from the user and will determine if it is a leap year or not.
Here is my leap year function so far (I do hope that this is the correct logic):
bool isLeapYear (int year){
int leapYear = 0;
//leapyear = 1 when true, = 0 when false
if ((year%400 == 0) && (year%100 != 100)) {
leapYear = 1;
}
else if (year%4 == 0) {
leapYear = 1;
}
else {
leapYear = 0;
}
if (leapYear == 1) {
return 1;
}
else {
return 0;
}
}
Here is a paraphrase of what I must do next:
You MUST use a loop that adds months one at a time to an accumulated sum.
Don't use any hardcoded values
Such as 152 for the first 5 months in a leap year
And to clarify, this is my first programming class and have been in this C++ class for just about a month now.
So it would be greatly appreciated if anyone could help me figure out how to do the loop statements to add the number of the months?
(IE: 12/31/2013 should be "365" in a non leap year, and "366" in a leap year).
I know this is wrong but this is what I have so far for a function "dayNumber" that simply return the number of days in the year to the main function (which is calling the dayNumber function):
int dayNumber (int day, int month, int year){
//variable declarations
int sumTotal = 0;
for ( int loop = 1; loop < month; loop++) {
sumTotal = (( month-1 ) * 31);
sumTotal = sumTotal + day + 1;
if ( (loop==4) || (loop=6) || (loop=9) ||
(loop==11) ) {
sumTotal = ( sumTotal - 1 );
}
else if ( isLeapYear(year) == 1 ) {
sumTotal = (sumTotal - 2);
}
else {
sumTotal = (sumTotal - 3);
}
}
return sumTotal;
}
I started to mess around with it to get to a proper value for days I knew but it kind of messed it up more, haha.
If anyone has any guidance on how to appropriately do a loop, I would be extremely greatful!:)
EDIT:
Alright, I think I may have answered my own question.
int dayNumber (int day, int month, int year){
//variable declarations
int sumTotal = 0;
for ( int loop = 1; loop < month; loop++) {
sumTotal = ( sumTotal + 31 );
if ( (loop==4) || (loop==6) || (loop==9) ||
(loop==11) ) {
sumTotal = ( sumTotal - 1 );
}
}
if ((month !=2) && (month > 1)) {
if (isLeapYear(year) ==1) {
sumTotal = ( sumTotal - 2 );
}
else {
sumTotal = ( sumTotal - 3);
}
}
else {
sumTotal = sumTotal;
}
sumTotal = sumTotal + day;
return sumTotal;
}
I definitely need to work on my loops.
I appreciate letting me know that my '=' should have been '=='!
I believe this is an appropriate code using a simple enough loop?
I will test some more dates. I've only tested the few provided on the class site so far.
I can't answer my own posts, I don't have enough reputation.
I know an answer has been accepted, but it took me some time writing my own, let's see if it can adds some informations overall.
Let's review this slowly.
First, your isLeapYear() function isn't completely right.
Without delving into the algorithm part, two or three things can be improved.
You're returning a bool, yet your return statements are returning ints. This isn't wrong in itself, but using the true and false keywords can improve the readability and consistency.
Instead of creating, assigning and returning a variable, you should instantly return your result.
Add spaces around your operators : year%400 should become year % 400.
Now your code.
This condition :
if ((year%400 == 0) && (year%100 != 100))
... especially this part :
(year%100 != 100)
Isn't doing what you expect.
Overall, the algorithm is as follow :
if year is not divisible by 4 then common year
else if year is not divisible by 100 then leap year
else if year is not divisible by 400 then common year
else leap year
Translating it in code:
/**/ if (year % 4 != 0)
return false;
else if (year % 100 != 0)
return true;
else if (year % 400 != 0)
return false;
else
return true;
Now let's simplify this a bit:
/**/ if (year % 4 == 0 && year % 100 != 0)
return true;
else if (year % 400 == 0)
return true;
else
return false;
Again:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
And finally, the whole boolean expression can be directly returned:
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
Now that your function is correct, let's try an algorithm to your dayNumber function :
If the date provided in parameters is considered correct, then the algorithm is quite simple :
Start sum from 0
Loop from 1 to month excluded
If month is Frebruary then add 29 if isLeapYear returns true, else 28
If month is January, March, May, July, August, October or December add 31
Else add 30
Add day to sum.
I know that giving detailed pseudocode helps more than a solution, but I'm not that good of a teacher yet :/ Good luck with this answer, and get some sleep when you're done :)
I'm assuming that dayNumber(8, 3, 1914) is supposed to return the ISO day number of 1914, March 8th.
What you want to do is the following:
procedure dayNumber(theDay, theMonth, theYear):
set answer to 1 // the first day of the year is day 1
for every month 'thisMonth', up to and excluding theMonth:
increment answer by the number of days in thisMonth
increment answer by (theDay - 1) // the first day of the month is monthday 1
return answer
In the iteration statement (or 'loop body'), there are three cases:
February: if it's a leap year, increment thisMonth by 29, otherwise increment by 28.
Short months (April, June, September, November): increment by 30 days.
Otherwise, long months (January, March, May, July, August, October, December): increment by 31 days.
This translates to:
if (thisMonth == 2) {
// February
if (isLeapYear(theYear))
thisMonth += 29;
else
thisMonth += 28;
} else if (thisMonth == 4 || thisMonth == 6 || thisMonth == 9 || thisMonth == 11) {
// Short month
thisMonth += 30;
} else {
// Long month
thisMonth += 31;
}
(Note: X += Y is, or should be, short for X = X + Y.)
The loop logic you use looks mostly correct to me, except for 1) off-by-one errors because you start with day 0, and 2) adding the monthday inside the loop rather than outside of it:
int dayNumber (int theDay, int theMonth, int theYear) {
int result = 1;
for (int thisMonth = 1; thisMonth < theMonth; thisMonth++) {
/* ... see above ... */
}
return result + theDay - 1;
}
Now, about making the iteration statement prettier, there are basically two ways (and if your course hasn't yet covered them, I of course recommend against using them in an answer). One is using a switch statement, but I'm really not a fan of them, and it doesn't provide much benefit over the code I already gave. The other would be to use arrays:
int dayNumber (int theDay, int theMonth, int theYear) {
int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31
, 31, 30, 31, 30, 31 }
int result = 1;
for (int thisMonth = 1; thisMonth < theMonth; thisMonth++) {
if (thisMonth == 2 && isLeapYear(theYear))
// Special case: February in a leap year.
result += 29;
else
/* Take the month length from the array.
* Because C++'s array indices begin at 0,
* but our first month is month 1,
* we have to subtract one from thisMonth.
*/
result += monthDays[thisMonth - 1];
}
return result + theDay - 1;
}
#include <ctime>
static int GetDaysInMonthOfTheDate(std::tm curDate)
{
std::tm date = curDate;
int i = 0;
for (i = 29; i <= 31; i++)
{
date.tm_mday = i;
mktime(&date);
if (date1->tm_mon != curDate.tm_mon)
{
break;
}
}
return i - 1;
}
I was trying to write a roll-your-own timezone converter and I needed a way of determining what the last possible day of the month was. Upon some research, I discovered the formulas for finding a leap year.
It's a small contribution, but maybe I'll save someone else the 20 minutes it took me to figure out and apply it.
This code accepts a signed short month, indexed at 0 (0 is January) and an int year that is indexed as 0 as well (2012 is 2012).
It returns a 1 indexed day (the 27th is the 27th, but in SYSTEMTIME structures, etc., you usually need 0 indexed - just a head's up).
short _get_max_day(short month, int year) {
if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || month == 9 || month == 11)
return 31;
else if(month == 3 || month == 5 || month == 8 || month == 10)
return 30;
else {
if(year % 4 == 0) {
if(year % 100 == 0) {
if(year % 400 == 0)
return 29;
return 28;
}
return 29;
}
return 28;
}
}
What about
#include <time.h>
#include <iostream>
int LastDay (int iMonth, int iYear)
{
struct tm when;
time_t lastday;
// Set up current month
when.tm_hour = 0;
when.tm_min = 0;
when.tm_sec = 0;
when.tm_mday = 1;
// Next month 0=Jan
if (iMonth == 12)
{
when.tm_mon = 0;
when.tm_year = iYear - 1900 + 1;
}
else
{
when.tm_mon = iMonth;
when.tm_year = iYear - 1900;
}
// Get the first day of the next month
lastday = mktime (&when);
// Subtract 1 day
lastday -= 86400;
// Convert back to date and time
when = *localtime (&lastday);
return when.tm_mday;
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int m = 1; m <= 12; m++)
std::cout << "Last day of " << m << " is " << LastDay (m, 2002) << std::endl;
return 0;
}
It prints out (for year 2002)...
Last day of 1 is 31
Last day of 2 is 28
Last day of 3 is 31
Last day of 4 is 30
Last day of 5 is 31
Last day of 6 is 30
Last day of 7 is 31
Last day of 8 is 31
Last day of 9 is 30
Last day of 10 is 31
Last day of 11 is 30
Last day of 12 is 31
I use a simple function that returns the whole date in the from of a (Standard) COleDateTime. It may not be as fast other options, but it is very effective, works for leap years and pretty fool proof.
This is the Code that I am using:
COleDateTime get_last_day_of_month(UINT month, UINT year)
{
if(month == 2)
{ // if month is feb, take last day of March and then go back one day
COleDateTime date(year, 3, 1, 0, 0, 0); // 1 March for Year
date -= 1; // go back one day (the standard class will take leap years into account)
return date;
}
else if(month == 4 || month == 6 || month == 9 || month == 11) return COleDateTime(year, month, 30, 0, 0, 0);
else return COleDateTime(year, month, 31, 0, 0, 0);
}
import datetime
from datetime import date
from dateutil.relativedelta import relativedelta
year = int((date.today()).strftime("%Y"))
month = list(range(1, 13, 1))
YearMonthDay = [(datetime.datetime(year, x, 1) + relativedelta(day=31)).strftime("%Y%m%d") for x in month]
print(YearMonthDay)
['20220131', '20220228', '20220331', '20220430', '20220531', '20220630', '20220731', '20220831', '20220930', '20221031', '20221130', '20221231']
In C++20:
#include <chrono>
std::chrono::day
get_max_day(std::chrono::month m, std::chrono::year y)
{
return (y/m/std::chrono::last).day();
}
If you really need it with a type-unsafe API:
int
get_max_day(int m, int y)
{
return unsigned{(std::chrono::last/m/y).day()};
}
Word Year, Month, Day;
TDateTime datum_tdatetime = Date();
// first day of actual month
datum_tdatetime.DecodeDate(&year, &month, &day);
day = 1;
datum_tdatetime = EncodeDate(year, month, day);
// last day of previous month
datum_tdatetime -= 1;
// first day of previous month
datum_tdatetime.DecodeDate(&year, &month, &day);
day = 1;
datum_tdatetime = EncodeDate(year, month, day);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Warning! Spoilers ahead!
You are given the following information, but you may prefer to do some
research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
At first, it seems like a simple problem. However, as I coded the solution, I ran into an odd problem - the answer should, in fact, be 171, but I get 173, whatever I do. I've looked over and over again my code, but nevertheless cannot find the bug.
#include <iostream>
using namespace std;
int main () {
int count = 0, days_in_month, days_passed = 1;
for (int i = 1900; i <= 2000; i++) {
for (int j = 1; j <= 12; j++) {
if (j == 4 || j == 6 || j == 9 || j == 11) {
days_in_month = 30;
} else if (j == 2) {
if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0)) {
days_in_month = 29;
} else {
days_in_month = 28;
}
} else {
days_in_month = 31;
}
if (days_passed % 7 == 0) {
count++;
}
days_passed += days_in_month;
}
}
cout << count << endl;
cin.ignore();
return 0;
}
Can anyone notice anything wrong with my code?
You are starting from 1900 i = 1900. The problem says "1 Jan 1901".