gpt4 book ai didi

c++ - 在 C++ 中将天数添加到给定日期

转载 作者:行者123 更新时间:2023-11-28 04:32:14 24 4
gpt4 key购买 nike

我正在尝试构建一个程序来返回特定日期后的日期。尽管我的代码没有任何类型的错误,但当我运行它时,由于某种我很难弄清楚的原因,输出日期略有偏差。你能帮助修复我的代码吗?

例如)输入:

2018
1
1

应该返回:

100: 2018 04 10
200: 2018 07 19
300: 2018 10 27

但事实并非如此......

提前谢谢你。

#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;
}

最佳答案

虽然您的代码还有很大的改进空间,但它确实按预期工作。你用输入声明:

2018
1
1

你期望的输出是:

100: 2018 04 10
200: 2018 07 19
300: 2018 10 27

但输出是:

100: 2018 04 11
200: 2018 07 20
300: 2018 10 28

这是正确的,因为您输入了 1 作为日期,然后在循环中每次都将其加上 100。因此,您的代码将返回第 101、201 和 301 天。

至于为什么在输出中看不到,所有计算都是使用 d 完成的,但是您的输出使用 x 作为标签, 分别是 100、200 和 300。

关于c++ - 在 C++ 中将天数添加到给定日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52572332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com