创建日期结构

Create a Date structure

本文关键字:结构 创建日期      更新时间:2024-09-28

这个问题让我创建一个名为Date的结构,以天、月和年为元素。将当前日期存储在结构中。现在在当前日期上添加45天并显示最终日期。

我写了代码:

#include<iostream>
using namespace std;
struct Date {
int days;
int months;
int years;
};
int main() {
Date date1;
cout << "Enter the day of the date " << endl;
cin >> date1.days;
while (date1.days > 31) {
cout << "The days can't be more than 31" << endl;
cout << "Enter the day of the date " << endl;
cin >> date1.days;
}
cout << "Enter the month of the date " << endl;
cin >> date1.months;
while (date1.months > 12) {
cout << "The month can't be more than 12" << endl;
cout << "Enter the month of the date " << endl;
cin >> date1.months;
}
cout << "Enter the year of the date " << endl;
cin >> date1.years;
cout << "The date is " << date1.days << "/" << date1.months << "/" << date1.years<<endl;
date1.months++;
date1.days+15;
if (date1.months == 12) {
date1.months = 1;
date1.years++;
}
if (date1.days==27) {
date1.days = 10;
}
if (date1.days == 28) {
date1.days =11;
}
if (date1.days == 29) {
date1.days = 12;
}
if (date1.days == 30) {
date1.days = 13;
}
if (date1.days == 31) {
date1.days = 14;
}
cout << "The date after adding 45 days is " << date1.days << "/" << date1.months <<"/"<< date1.years;
}

如果统计数据根本不起作用,为什么以及该怎么办?

date1.days+15;是非操作,结果立即丢弃,并且days不会更改。改为使用+=运算符:

date1.days += 15;

无论如何,你增加日期的方式确实是不准确的。尝试更像以下的方法(我相信有更有效的方法来实现这一点,但它应该会给你一个想法(:

#include <iostream>
#include <limits>
using namespace std;
bool isLeapYear(int year)
{
return (
((year % 4 == 0) && (year % 100 != 0)) ||
(year % 400 == 0)
);
}
int lastDayOf(int month, int year)
{
if (month == 2)
return isLeapYear(year) ? 29 : 28;
else if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
else
return 31;
}
struct Date {
int day;
int month;
int year;
Date& operator+=(int days)
{
// TODO: handle a negative value for subtracting days...
int d = day + days;
int lastDay = lastDayOf(month, year);
while (d > lastDay)
{
d -= lastDay;
if (++month == 13)
{
++year;
month = 1;
}
lastDay = lastDayOf(month, year);
}
day = d;
return *this;
}
// TODO: implement operator-=() for subtracting days...
};
istream& operator>>(istream &in, Date &d)
{
if (in >> d.day >> d.month >> d.year)
{
if (d.month < 1 || d.month > 12 ||
d.day < 1 || d.day > lastDayOf(d.month, d.year))
{
in.setstate(ios_base::failbit);
}
}
return in;
}
int main() {
Date date1;
cout << "Enter the day, month, and year of the date" << endl;
while (!(cin >> date1))
{
cout << "Invalidate date!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "Enter a new day, month, and year of the date" << endl;
}
date1 += 45;
cout << "The date after adding 45 days is " << date1.day << "/" << date1.month << "/" << date1.year;
}

一般结构

将输入、工作和输出分离为单独的功能。真正的肉应该是一个接受输入(日期(并返回结果(另一个日期(的函数。

然后,你可以有一个像main这样的交互式驱动程序,它会提示用户,或者一组预先编码的示例自动尝试,而不必每次都键入它们。它也可以自动检查结果!

算法

你的代码根本不起作用。您没有添加45天。在用编码语言表达之前,您需要了解要做什么。

想想";溢出和进位";。

您将其标记为oop

这并没有任何面向对象的东西。如果这是一个关于面向对象编程的练习,那么你还远远不够。