Reputation: 3
I'm trying to build a program that returns the dates after certain days. Even though my code has no any sort of error, when I run it, the output dates are slightly off for some reason I have hard time figuring out. Could you help fix my code?
For example) Input:
2018
1
1
should return:
100: 2018 04 10
200: 2018 07 19
300: 2018 10 27
but it doesn't....
Thank you in advance.
#include <iostream>
using namespace std;
int main() {
//declare variables
int y,m,d;
int yoon=0;//assume to be normal year at first
//take user input
cin>>y>>m>>d;
//separate leap year & normal year (leap year: 1 , normal year = 0)
if (y % 4 ==0){
yoon = 1;
if (y % 100 ==0) {
yoon = 0;
if (y % 400 == 0){
yoon= 1;
}
}
}
//iterate for 100, 200, 300 days
for (int x=100;x<=300;x+=100) {
//add days to the given date
d+=100;
//iterate untill there is no day overflow
while(true)
{
//check the number of days in given month and subtract if it overflows
if ((m == 4 || m==6 || m==9 || m==11) && d>30)
{
d-=30;
m++;
}
//different days for leap year
else if (m==2 && d>29 && yoon ==1)
{
d-=29;
m++;
}
//different days for normal year
else if (m==2 && d>28 && yoon ==0)
{
d-=28;
m++;
}
else if (d>31)
{
d-=31;
m++;
//check for leap year if the year changes
if (m==13){
m=1;
y+=1;
if (y % 4 ==0){
yoon = 1;
if (y % 100 ==0) {
yoon = 0;
if (y % 400 == 0){
yoon= 1;
}
}
}
}
}
else
{
break;
}
}
//output
cout<<x<<":"<<" "<<y<<" ";
if (m>0 && m<10){cout<<0;}
cout<<m<<" ";
if (d>0 && d<10){cout<<0;}
cout<<d<<endl;
}
return 0;
}
Upvotes: 0
Views: 1897
Reputation: 956
Although there's much room for improvement in your code, it does work as expected. You state that with input:
2018
1
1
you expect the output to be:
100: 2018 04 10
200: 2018 07 19
300: 2018 10 27
yet the output is:
100: 2018 04 11
200: 2018 07 20
300: 2018 10 28
This is correct since you entered 1 as the day and then add 100 to that every time inside your loop. Consequently, your code will return days 101, 201 and 301.
As for why you couldn't see that in your output, all calculations are done with d
, yet your output uses x
as the label, which is 100, 200 and 300 respectively.
Upvotes: 1