I am trying to create a program that finds out how many months they have been alive, but have been running into some issues. Here is my function so far:
int getResult(int year, month, day, endResult)
{
int thisYear, thisMonth, thisDay;
year = thisYear - year;
year *= 12;
}
And what I'm trying to accomplish would show an output like:
Output:
What year were you born?
1989
What month were you born?
5
What day were you born?
23
You are x months old.
I was going to continue with months but then I realized, what if the month they were born is in after this month or before? So, if anyone has any tips on how to calculate that, I'd appreciate it.
Let's see. First, let's say now is:
year_now and month_now
and your birthday is:
year_birth and month_birth
Now, we go case by case:
month_now == month_birth: as you have already computed:
months_old = (year_now-year_birth)*12
month_now > month_birth: easily, you have:
months_old = (year_now-year_birth)*12 + (month_now-month_birth)
month_now < month_birth: in this case, (year_now-year_birth)*12 gives you more months then necessary, and you have to subtract:
months_old = (year_now-year_birth)*12 - (month_birth-month_now)
Now if you look carefully, you will see that they are all in fact the same formula:
months_old = (year_now-year_birth)*12 + (month_now-month_birth)
(in the third case, month_now-month_birth is negative)
months = (thisyear-years)*12+(thisMonth-months)
if(months < 0)
System.out.println("Invalid info")
else{
//DO YOUR THANG BRO
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a program that is getting a date from some protocol, in format of DD/MM/YYYY.
The Problem is that I need to know the info of that day(day of the week, day in the year...) and I don't know how to do it.
Usually, when I want to get a day info, I am using time(time_t*) and convert the result to tm struct using localltime_r(tm*, time_t*) and then I have everything i need.
But in this case, this is not the current time(so I can not use time(time_t*)) and I don't have nothing except the date.
I can create a new tm struct and fill only tm_year, tm_mon, tm_mday and use mktime(tm*), but I am not sure if this will give me the right detail's of the desired date.
You might consider using Howard Hinnant's free, open-source date/time library. It works with C++11 and later, ported to gcc, clang and VS. It has been accepted into the C++20 draft specification.
Example code:
#include "date/date.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace std;
using namespace date;
istringstream in{"09/07/2018"};
sys_days sd;
in >> parse("%d/%m/%Y", sd);
cout << "Day of the week is " << weekday{sd} << '\n';
cout << "Day of the year is " << sd - sys_days{year_month_day{sd}.year()/1/0} << '\n';
}
Output:
Day of the week is Mon
Day of the year is 190d
If you would rather do the computations yourself, here are extremely efficient non-iterative public domain algorithms for calendrical computations. The library referenced above is nothing but a type-safe wrapper around these algorithms with more pleasant syntax.
In case you wanted to get write methods which get the day of week/year as opposed to using a library, here's what I would do.
You're going to need to take leap years into account. For any given year, determine whether or not it is a leap year. Something like this would work (using a formula found here: https://en.wikipedia.org/wiki/Leap_year#Algorithm:
bool isLeapYear(short year)
{
bool leapYear = false;
if (((year % 4 == 0 && year % 100 != 0)) || (year % 400 == 0))
leapYear = true;
return leapYear;
}
From this, calculating the day of the year is straightforward. Simply add up all the days for each month, if it is a leap year, add 29 days onto your tally for day of year if you come across February.
As for finding the day of the week, it really helps if you start with some lower bound for the year (in this case LOWYEAR = 1760) and start with the first day of that year (STARTDAYOFWEEK = 2). Each day of the week is corresponds to a number (0-6) where Sunday is 0, Monday is 1, etc.
int DayOfWeek(void)
{
//jan 1 1760 was tuesday (2)
short dayCount = STARTDAYOFWEEK;
for (unsigned i = LOWYEAR; i < year; i++)
{
if (isLeapYear(i))
dayCount += 2;
else
dayCount++;
}
return (dayCount + dayOfYear) - 1) % DAYSINWEEK;
}
Finding the day of week is now really easy, after calculating dayCount, the day of week is found by adding dayCount with dayOfYear and modding by DAYSINWEEK (6).
The resulting number will correspond to the day of week (0-6).
I have an exercice, which I am having a little trouble with.
I must create a calculator which takes two parameters: Start date and days to add (except saturday and sunday, only business days, from monday to friday). Another thing is that the sum has to include the start date.
E.g. let's take the start day July 12th 2016, and add 8 days, which correspond to July 21th 2016 (Saturday and Sunday excluded, and Tuesday, July 21th 2016 is counted as one day).
I hope I'm clear.
I tried to code something, but it is not working.
// rStringGridEd1->IntCells[3][row] is a custom stringgrid
// and correspond to the number of days to add, j is the
// counter for the loop
while (j < rStringGridEd1->IntCells[3][row])
{
if (DayOfWeek(date) != 1 || DayOfWeek(date) !=7)
{
// if current date (TDate date = "12/07/16") is not Saturday or Sunday increment date by one day
date++;
}
else if(DayOfWeek(date) == 1)
{
//If date correspond to sunday increment the date by one and j the counter by one
date=date+1;
j++;
}
else if(DayOfWeek(date) == 7)
{
//If date correspond to saturday increment the date by two days and j the counter by one
date=date+2;
j++;
}
j++;
}
Can anyone help me, please?
Here is what Lee Painton's excellent (and up-voted) answer would look like using this free, open-source C++11/14 date library which is built on top of <chrono>:
#include "date.h"
#include <iostream>
date::year_month_day
get_end_job_date(date::year_month_day start, date::days length)
{
using namespace date;
--length;
auto w = weeks{length / days{5}};
length %= 5;
auto end = sys_days{start} + w + length;
auto wd = weekday{end};
if (wd == sat)
end += days{2};
else if (wd == sun)
end += days{1};
return end;
}
You could exercise it like this:
int
main()
{
using namespace date::literals;
std::cout << get_end_job_date(12_d/jul/2016, date::days{8}) << '\n';
}
Which outputs:
2016-07-21
This simplistic calculator has a precondition that start is not on a weekend. If that is not a desirable precondition then you could detect that prior to the computation and increment start internally by a day or two.
The date library takes care of things like the relationship between days and weeks, and how to add days to a date. It is based on very efficient (non-iterative) algorithms shown and described here.
If you aren't required to use a loop then you might want to consider refactoring your solution with a simpler calculation. Consider, for example, that every five business days automatically adds seven days to the date. Thus using the quotient and remainder of the days to add should tell you how many total days to add to your date variable without resorting to a brute force loop.
Since it's an exercise I won't get into specifics of code, but a few things to consider might be how you can figure out what day of the week you end on knowing the day that you started on. Also, if you end on a friday what happens with the weekend that immediately follows it.
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)?
I don't seem to get the right answer or find the bug. I get the answer 85.
int main(){
int month[12]={31,0,31,30,31,30,31,31,30,31,30,31};
int j=0;
int i= 1901;
int day=1;
int sunday=0;
for(i=1901;i<2001;i++) {
if( i % 4==0 ){
month[1]=29;
}
else {
month[1]=28;
}
for (j=0;j<12;j++){
if (day % 7 ==0){
sunday++;
}
day+=month[j];
j++;
}
}
cout<< sunday<<endl;
cin.ignore();
return 0;
}
Bisides what Bathsheba already pointed out in his answer You are also skipping every other month. In your for loop you increment j at the end of the loop and then j will get incremented again at the start of the next loop.
for (j=0;j<12;j++){
if (day % 7 ==0){
sunday++;
}
day+=month[j];
j++;<--------------get rid of this
}
Given that the normal definition of the 20th century is from 1-Jan-1900 to 31-Dec-1999, consider changing the loop to for (i = 1900; i < 2000; ++i).
If you need the range to be from 1-Jan-1901 to 31-Dec-2000 then note that 1-Jan-
1901 was a Tuesday and so the starting value of day needs to be 2.
You also have a spurious j++; in your month iteration (acknowledge #NathanOliver)
Other than that, the algorithm looks fine. Although I don't like the continuous writing to month.
In order that a device (with limited memory) is able to manage its own timezone and daylight savings, I'm trying to calculate daylight savings triggers for 85 time zones based on a simplified description of each timezone. I have access to minimal C and C++ libraries within the device. The format of the timezone (inc. DST) description for each time zone is as follows:
UTC - the base time and date from system clock
GMTOffsetMinutes - offset from GMT with DST inactive
DSTDeltaMinutes - modifier to above with DST active (as applicable to TZ)
DSTStartMonth - month in which DST becomes active
DSTStartNthOccurranceOfDay - the nth occurrence of the day name in month
DSTDayOfWeek - Sun = 0 through to Sat = 6
DSTStartHour - hour at which DST becomes active
DSTStartMinute - minute at which DST becomes active
and corresponding EndMonth, EndNth..., EndHour, EndMinute
I have found numerous examples going the other way, i.e. starting with the date, but they involve using the modulus, keeping the remainder and dropping the quotient hence I have been unable to transpose the formula to suit my needs.
I also tried to reuse the standard "Jan = 6, Feb = 2, Mar = 2, Apr = 5, May = 0, etc. modifier table and year modifiers from the "tell me what day the 25th of June, 2067 is?" party trick and developed the following algorithm.
Date = DayOfWeek + ((NthOccuranceOfDay - 1) x 7 ) - MonthCode - YearCode
This worked for the first 6 random test dates I selected but then I started to see dates for which it failed. Is it possible that the basic algorithm is sound but I'm missing a further modifier or maybe that I'm applying the modifiers incorrectly?
Is there another solution I could utilize?
Using this open source, cross platform date library, one can write:
#include "date.h"
#include <iostream>
int
main()
{
using namespace date;
year_month_day us_daylight_starts = sys_days(sun[2]/mar/2015);
year_month_day us_daylight_ends = sys_days(sun[1]/nov/2015);
std::cout << us_daylight_starts << '\n';
std::cout << us_daylight_ends << '\n';
}
which will output:
2015-03-08
2015-11-01
The formulas this library is based on are in the public domain and documented here.
The algorithms paper has very complete unit tests validating the date algorithms over a range of millions of years (a far larger range than is necessary).
Sometimes daylight savings rules are written in terms of the last weekday of a month. That is just as easily handled:
year_month_day ymd = sys_days(sun[last]/nov/2015);
std::cout << ymd << '\n'; // 2015-11-29
That formula will be off by one week (or even two weeks) if MonthCode + YearCode is greater than or equal to DayOfWeek, because in that case you will be counting NthOccurenceOfDay from a negative date.
As an alternative, with no tables, you can compute the day of week of the first of the month using, for example, Zeller's algorithm:
int NthOccurrence(int year, int month, int n, int dayOfWeek) {
// year is the current year (eg. 2015)
// month is the target month (January == 1...December == 12)
// Finds the date of the nth dayOfWeek (Sun == 0...Sat == 6)
// Adjust month and year
if (month < 3) { --year, month += 12; }
// The gregorian calendar is a 400-year cycle
year = year % 400;
// There are no leap years in years 100, 200 and 300 of the cycle.
int century = year / 100;
int leaps = year / 4 - century;
// A normal year is 52 weeks and 1 day, so the calendar advances one day.
// In a leap year, it advances two days.
int advances = year + leaps;
// This is either magic or carefully contrived,
// depending on how you look at it:
int month_offset = (13 * (month + 1)) / 5;
// From which, we can compute the day of week of the first of the month:
int first = (month_offset + advances) % 7;
// If the dayOfWeek we're looking for is at least the day we just
// computed, we just add the difference. Otherwise, we need to add 7.
// Then we just add the desired number of weeks.
int offset = dayOfWeek - first;
if (offset < 0) offset += 7;
return 1 + offset + (n - 1) * 7;
}
Hi to all thank all in advance to those who tried to answer or answer and part of this question.
Calculate the sum of the digits of the year.
Calculate the absolute value of the difference between the year and the ’reverse’ of the year.
Calculate the number of even factors of the day.
Calculate the greatest common divisor of the day, month and year.
Calculate the number of steps required to solve the Collatz problem for
the month
These are my tasks that I need to fulfill, as Engineering student this how far I went in this. In the following codes I expect something like this
19
90
0
1
0
T M B B
The answer that I get is
Please enter your birthdate (dd mm yyyy): 12 11 1981
19
8468304
Press any key to continue . . .
8468304
How to get it right I know that my equation is right or(formula, method). However this is what I know.
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
cout << "Please enter your birthdate (dd mm yyyy): ";
int day, month, year, count,rev;
int sum = 0;
cin >> day>> month >>year;
while (year!=0)
{
int count = year%10;
sum +=count;
year /= 10;
}
while(year>0)
{
rev = year%10;
year=year/10;
}
cout<<sum<<endl;
cout << rev;
system ("pause");
return 0;
}//end main
Please help!
After your first loop, while (year != 0), you don't reset the value of year, so it remains at zero and the second loop doesn't execute at all.
You need to save the value of year and use it when you start the second loop.
Just a note on organisation: I'd suggest to write a subroutine/function for every task, like
int digit_sum(int year) {
/* ... */
return sum;
}
int reverse_difference(int year) {
/* ... */
return diff;
}
and so on. This way you'll also prevent errors like modifying the year variable during the first calculation without saving the original value (which you did, as David Winant already pointed out).