-1

I'm learning C++ and I've gone through some lessons and now I was doing this assignment, but I can't get it to work in the currently written code.

This the code:

int main() {
  double weight;
  char planets;

  std::cout << "Please enter your current earth weight: ";
  std::cin >> weight;

  std::cout << "Which planet would you like to go?\n";
  std::cout << "Mercury,Venus,Mars,Jupiter,Saturn,Uranus,Neptune \n";
  std::cout << "Which planet are you visiting? \n";
  std::cin >> planets;

  if (planets == Mercury) {
    weight = weight * 0.38;
  }

  else if (planets == Venus) {
    weight = weight * 0.91;
  }

  else if (planets == Mars) {
    weight = weight * 0.38;
  }

  else if (planets == Jupiter) {
    weight = weight * 2.34;
  }

  else if (planets== Saturn) {
    weight = weight * 1.06;
  }

  else if (planets == Uranus) {
    weight = weight * 0.92;
  }

  else if (planets == Neptune) {
    weight = weight * 1.19;
  }

  std::cout << "Ti do ishe " << weight << "\n";
}

When I change the variable to int x; and afterward replace the input data with numbers, it works but as I said I want it to work by using names.

What's wrong?

GSerg
  • 76,472
  • 17
  • 159
  • 346
Alaris
  • 93
  • 1
  • 6

2 Answers2

2

You are comparing your planets input with variables named Mercury, Venus, etc. which are not defined, remember strings go inside " "(quotes). Also, your planets input is type char which means you can't compare it with "Mercury" or any other string. So for comparison to work, you need your planets variable to be of type string.

int main() {
  double weight;
  std::string planets;

  std::cout << "Please enter your current earth weight: ";
  std::cin >> weight;

  std::cout << "Which planet would you like to go?\n";
  std::cout << "Mercury,Venus,Mars,Jupiter,Saturn,Uranus,Neptune \n";
  std::cout << "Which planet are you visiting? \n";
  std::cin >> planets;

  if (planets == "Mercury") {
    weight = weight * 0.38;
  }

  else if (planets == "Venus") {
    weight = weight * 0.91;
  }

  else if (planets == "Mars") {
    weight = weight * 0.38;
  }

  else if (planets == "Jupiter") {
    weight = weight * 2.34;
  }

  else if (planets== "Saturn") {
    weight = weight * 1.06;
  }

  else if (planets == "Uranus") {
    weight = weight * 0.92;
  }

  else if (planets == "Neptune") {
    weight = weight * 1.19;
  }

  std::cout << "Ti do ishe " << weight << "\n";
}
0

Use std::string instead of char would be a solution. Don't forget to use the quotation marks. If you want to use char you cannot work with the full names of the planets, only with characters, i. e.'M' for Mercury: if (planets == 'M').

Heiko C.
  • 1
  • 1