C++ reverse number with digit adding
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 BThe answer that I get is
Please enter your birthdate (dd mm yyyy): 12 11 1981
19 8468304 Press any key to continue . . . 8468304How 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).
精彩评论