C++ age calculation function I have written code to get user input for their bir
ID: 3589986 • Letter: C
Question
C++ age calculation function
I have written code to get user input for their birth day, month, and year (all ints). All of that gets put in a struct called Date which I initialize in main with Date input for the birth date and Date output for the desired date. therefore to reference them you would use input.day, input.month and input.year and so on using output instead of input. What I need now is a function to take these structs and calculate the users age based on their input. You can just call the function CalculateAge.
Explanation / Answer
#include <iostream>
using namespace std;
struct Date //structure declaration
{
int day;
int month;
int year;
};
struct Date CalculateAge(struct Date input,struct Date output) //function to calculate age
{
struct Date age ;
age.day = output.day - input.day;
if(age.day < 0)
age.day = 0;
age.month = output.month - input.month;
if(age.month < 0)
age.month = 0;
age.year = output.year - input.year;
return age;
}
int main() {
int day,month,year;
//input birthday
cout<<"Enter your birthday in day , month and year : ";
cin>>day>>month>>year;
struct Date input = {day,month,year};
cout<<" Enter the date upto which to calculate age in day , month and year : ";
cin>>day>>month>>year;
struct Date output = {day,month,year};
struct Date age = CalculateAge(input,output); //function call
cout<<" Age : "<<age.year<<" years "<<age.month<<" months "<<age.day<<" days.";
return 0;
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.