#include <iostream>
using std::cout;
using std::cin;
int main()
{
char name[31];
int age;
int difference;
int my_age=31;
difference = (age - my_age);
cout << "What's your name?\n";
cin >> name;
cout << "How old are you?\n";
cin >> age;
if (age == 31)
{
cout << "Nice to meet you " << name << ", I'm " << age << " years old aswell";
}
else
{
cout << "Nice to meet you " << name << ", it differs " << difference << " years between us";
}
system("pause");
return 0;
}
When I type in for instance 41 as age it says: "Nice to meet you name, it differs 2009187012 years between us". I would like to know what I've done wrong. I would also like to know if I type in a number that's smaller than 31 how I can make the smallest number subtract from the larger one. I hope you understand what I mean.
You assigned the value of (age-my_age) to difference before getting the the users age, so you ended up getting garbage for an answer.
There is an absolute value function abs(), that you can use to output the positive difference.
abs(12) = 12
and
abs(-13) = 13
To use it put #include<cmath> at the top of your code.
Thanks for all the replies, I prefer Danny Toledos method since that was closest to my "knowledge" at the time. I now saw what I did wrong, thanks for pointing that out Browni3141.