C++ reverse number with digit adding - c++

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).

Related

Same math and numbers different answers?

im writing a simple program that you give a number of days and it gives back the number of years weeks and days that equal to the numbers of days you give.
but i noticed that you can get two different answers even tho when i checked the math it makes sense in both cases .
can someone please please explain to me why the answers are different and which one is correct
#include<iostream>
using namespace std;
int main()
{
int y;
int d,w;
int Days;
cin>>d;
y=d/365;
int LessThanAYearDays = d%365;
Days=LessThanAYearDays%7;
w=LessThanAYearDays/7;
int SameDays = d%7;
cout<<"answer1 is : "<<y<<" "<<w<<" "<<Days<< "\n";
cout<<"answer2 is : "<<y<<" "<<w<<" "<<SameDays<< "\n";
return 0;
}
There are not an exact multiple of weeks in a year, so you are displaying different things. They will be the same in years divisible by 7.
E.g. Assume that a given year starts on a Tuesday.
Days corresponds to how many days past the last Tuesday you are.
SameDays corresponds to what day you are on.
See also the distinction that std makes between a std::chrono::duration, which is a count of time, and a std::chrono::time_point, which is a count of time since a particular date.

C++ Days Passed in the Year

Hello i been doing some program , my program is to get the number of days passed in the year. Now when i try to run and the output gives me "4438232".
For example if the user enter (mm-dd-yy) 3-18-2013, then the reaming days passed in the year is 77.
Does this code make sense on getting the reaming days passed in the year?
void dateType::Num_DayPassed()
{
int sum;
int yy = 365;
if (month ==1)
{
cout<<"Number of days Passed in the Year: "<<sum<<endl;
day=31;
sum=day-yy;
}
........
continued until month 12..
Full Code
Output
C++ programs run top-to-bottom. You're outputting sum before you set it.

Method to calculate business days

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.

Counting Sundays in c++;

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.

How do I use getline and stringstream to parse formatted date and time input?

I have only been working on c++ for about a month. I am not really understanding how it works, however I need to write a program for school. I used a void function and it seems to be working so far,but I have no idea what to do next I am lost at line 44, I am not sure how to make it work, is there a way to take a value from a certain string? If the value is in both strings how would I determine which value? Here is my assignment:
A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. People who park their cars for longer than 24 hours will pay $8.00 per day.
Write a program that calculates and prints the parking charges. The inputs to your program are the date and time when a car enters the parking garage, and the date and time when the same car leaves the parking garage. Both inputs are in the format of YY/MM/DD hh:mm
Here's the code I've written so far:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
#include <sstream>
using namespace std;
stringstream ss;
string enter_date;
string enter_time;
string exit_date;
string exit_time;
int calculatecharge;
int num;
int i;
int year;
int month;
int ddmmyyChar;
int dayStr;
string line;
int x;
void atk()
{
getline (cin,line); // This is the line entered by the user
stringstream ss1(line); // Use stringstream to interpret that line
ss >> enter_date >> enter_time;
stringstream ss2(enter_date); // Use stringstream to interpret date
string year, month, day;
getline (ss2, year, '/');
}
int main()
{
cout << "Please enter the date and time the car is entering "<< endl
<< "the parking garage in the following format: YY/MM/DD hh:mm"<< endl;
atk();
cout << "Please enter the date and time the car is exiting "<< endl
<< "the parking garage in the following format: YY/MM/DD hh:mm"<< endl;
atk();
if (hr - hr < 3)
cout<<"Parking fee due: $2.00" << endl;
Write a program that calculates and prints the parking charges.
This is the goal of our program. Basically, this is the output.
The inputs to your program are the date and time when a car enters the
parking garage, and the date and time when the same car leaves the
parking garage. Both inputs are in the format of YY/MM/DD hh:mm
So, we want some way of translating the date format entered as a string into a time difference. You could store the time in an int, which represents the amount of minutes elapsed during the parking period (I choose minutes since this is the smallest time period inputted). The challenge here is the parsing of the string into this integer.
You could write a function like this:
int parseDate( std::string dateStr )
{
// Format: YY/MM/DD hh:mm
int year = atoi( dateStr.substr( 0, 2 ).c_str() );
int month = atoi( dateStr.substr( 3, 2 ).c_str() );
int day = atoi( dateStr.substr( 6, 2 ).c_str() );
int hour = atoi( dateStr.substr( 9, 2 ).c_str() );
int min = atoi( dateStr.substr( 12, 2 ).c_str() );
// Now calculate no. of mins and return this
int totalMins = 0;
totalMins += ( year * 365 * 24 * 60 ); // Warning: may not be accurate enough
totalMins += ( month * 30 * 24 * 60 ); // in terms of leap years and the fact
totalMins += ( day * 24 * 60 ); // that some months have 31 days
totalMins += ( hour * 60 );
totalMins += ( min );
return totalMins;
}
Careful! My function here is just an illustration, and does not take into account subtleties like leap years and varying month length. You will probably need to improve on it. The important thing is to recognise that it attempts to take a string and return the number of minutes that have elapsed since year '00. This means we simply have to subtract two integers from the two date strings to find the elapsed time:
int startTime = parseDate( startDateString );
int endTime = parseDate( endDateString );
int elapsedTime = endTime - startTime; // elapsedTime is no. of minutes parked
This is probably the hardest part of the problem, once you have this worked out, the rest should be more straightforward. I will give you a few more tips:
A parking garage charges a $2.00 minimum fee to park for up to three
hours.
Basically just a flat rate: No matter what, the output variable that describes the cost should be equal to at least 2.00.
The garage charges an additional $0.50 per hour for each hour
or part thereof in excess of three hours.
Work out the amount of hours elapsed past three hours - subtract 180 from elapsedTime. If this is greater than 0, then divide it by 60 and store the result in a float (since it is not necessarily an integer result), called, say, excessHours. Use excessHours = floor( excessHours ) + 1; to round this number up. Now multiply this by 0.5; this is the extra cost. (Try to understand why this works mathematically).
The maximum charge for any
given 24-hour period is $10.00. People who park their cars for longer
than 24 hours will pay $8.00 per day.
I will leave this up to you to work out, since this is homework after all. Hopefully I have provided enough here for you to get the gist of what needs to be done. There are many possible approaches to this problem too, this is just one, and may or may not be "the best".
First of all as both the string for the date and the string for the time are continuous(contain no spaces), you do not need to use stringstream to parse the line. You can read the date and time just like this:
cin >> enter_date >> enter_time;
cin >> exit_date >> exit_time;
Now what you need is to convert these strings to actual dates and times. As the format of both is fixed you can write something like this:
void parse_date(const string& date_string, int& y, int& m, int& d) {
y = (date_string[0] - '0')*10 + date_string[1] - '0'; // YY/../..
m = (date_string[3] - '0')*10 + date_string[4] - '0'; // ../mm/..
d = (date_string[6] - '0')*10 + date_string[7] - '0'; // ../../dd
}
Of course this code is somewhat ugly and can be written in better way but I believe this way it is easier to understand. Having this function it should be obvious how to write this one:
void parse_time(const string& time_string, int& h, int &m);
Now that you have the date and time parsed, you need to implement a method that subtracts two dates. IN fact what you care about is the number of hours that elapsed from the enter date time to the exit date time rounded up. What I suggest here is that you convert the dates to number of days from some initial moment(say 00/01/01) and then subtract the two values. Then convert both times to number of minutes since 00:00 and again subtract them. This is not language specific so I believe these tips should be enough. Again using some built-in libraries this can be done easier but I don't think this is the idea of your assignment.
After you have the number of hours rounded up all you need to do is actually to implement the rules in the statement. This will only take a few ifs and is in fact quite easy.
Hope this helps. I am purposefully not giving more detailed explanations so that there is something left for you to think about. After all this is homework and is meant to make you think how to do it.
You don't need to perform separate input reading and parsing operations. You could pass the necessary variables by reference and read the input directly into the variables using stringstream. I would use a structure to store the date and time and overload operator- with an algorithm for subtracting two date/time values. Here's how I would do it:
#include <iostream>
#include <sstream>
using namespace std;
struct DateTime {
// Variables for each part of the date and time
int year, month, day, hour, minute;
// Naive date and time subtraction algorithm
int operator-(const DateTime& rval) const {
// Total minutes for left side of operator
int lvalMinutes = 525600 * year
+ 43200 * month
+ 1440 * day
+ 60 * hour
+ minute;
// Total minutes for right side of operator
int rvalMinutes = 525600 * rval.year
+ 43200 * rval.month
+ 1440 * rval.day
+ 60 * rval.hour
+ rval.minute;
// Subtract the total minutes to determine the difference between
// the two DateTime's and return the result.
return lvalMinutes - rvalMinutes;
}
};
bool inputDateTime(DateTime& dt) {
// A string used to store user input.
string line;
// A dummy variable for handling separator characters like "/" and ":".
char dummy;
// Read the user's input.
getline(cin, line);
stringstream lineStream(line);
// Parse the input and store each value into the correct variables.
lineStream >> dt.year >> dummy >> dt.month >> dummy >> dt.day >> dummy
>> dt.hour >> dummy >> dt.minute;
// If input was invalid, print an error and return false to signal failure
// to the caller. Otherwise, return true to indicate success.
if(!lineStream) {
cerr << "You entered an invalid date/time value." << endl;
return false;
} else
return true;
}
From here, in the main() function, declare two DateTime structures, one for the entry time and one for the exit time. Then read in both DateTime's, subtract the entry time from the exit time, and use the result to generate the correct output.