Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the c++ program outputting a wrong negative number

#include <iostream>

int main() {
  
  int woe; // weight on earth
  int wom = woe * 2; // weight on mars
  
  std::cout << "Enter your weight on earth: \n";
  std::cin >> woe;

  std::cout << "Your weight on mars would be " << wom << " Pounds\n";
    
}

Hello everyone I just started to learn c++ and when I try to multiply the variable "woe" by 2 it prints a big negative number like "-2123145280 Pounds" when I input 100. please help thank.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When you just define an integer variable without assignment in C++ it takes a random number, then you are just doubling that random number in wom variable and after that you take input. A more correct version of your code is:

#include <iostream>

int main() {
  int woe = 0; // weight on earth

  std::cout << "Enter your weight on earth: \n";
  std::cin >> woe;

  int wom = woe * 2; // weight on mars
  std::cout << "Your weight on mars would be " << wom << " Pounds\n";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading