Alt dog years gone wrong

Hi there! I completed the first dog year project and it worked perfectly, but I wanted to play around and have the user input the age instead. When I changed my code to have the user input the age, it tells me that the dog is 1541447885 years old. I’m sorry if the error is obvious- Any help would be appreciated! :slight_smile:

#include <iostream>

int main() {
  //dog age entered
  int dog_age;
  //First two years of a dog's life is 21 human years.
  int early_years = 21;
  //Each following year counts as 4 human years. Minus the first two years for the 21 years.
  int later_years = (dog_age-2) * 4;
  int human_years = early_years + later_years;
  
  std::cout << "Enter your dog's age: \n";
  std::cin >> dog_age;
  std::cout << "My name is Luna! Ruff ruff, I am " << human_years << " years old in human years.\n";
}

The statements will be executed top to bottom. You declared dog_age but didn’t initialize it (which is fine). You then use this uninitialized variable in the calculation of later_years. Using the uninitialized variable in a calculation causes undefined behavior. Have a look at:
https://en.cppreference.com/book/uninitialized

You do read in the user input and assign it to dog_age, but the calculations have already been done before this statement is executed.
If you change the sequence of statements, your code should work.

#include <iostream>

int main() {
    
  //dog age entered
  int dog_age;
  
  std::cout << "Enter your dog's age: \n";
  std::cin >> dog_age;
  
  //First two years of a dog's life is 21 human years.
  int early_years = 21;
  //Each following year counts as 4 human years. Minus the first two years for the 21 years.
  int later_years = (dog_age-2) * 4;
  int human_years = early_years + later_years;
  
  std::cout << "My name is Luna! Ruff ruff, I am " << human_years << " years old in human years.\n";
}
2 Likes