user3404737
user3404737

Reputation: 11

Equality comparison in if-statement

Sorry about this question, this is my first C++ project and I'm a little confused. I'm asking the user to input 3 separate things. For example, I'm starting off with a number, 80. I'm asking the user 3 questions. 1) Do you like blue or yellow? Type 1 for blue, 2 for yellow. If the user enters 1 for blue, multiply the number 80 by 2. If they enter 2 for yellow, multiply 80 by 3.

Can somebody let me know if this looks like it's on the right track? Thanks and sorry again for the beginner question.

cout << "Please enter a color blue or yellow. Type 1 for Blue, 2 for Yellow";
cin >> bp1;
// Multiply by 2 if Blue is chosen, 3 if Yellow is chosen.
if (bp1 = 1)
num = num*2;
if (bp1 = 2)
num = num*3;

Upvotes: 0

Views: 103

Answers (4)

Jabberwocky
Jabberwocky

Reputation: 50778

Even simpler:

Instead of:

if(bp1 == 1)
  num = num * 2;
else if (bp1 == 2)
  num = num * 3;

you can write this

  num = num * (bp + 1)

or even

  num *= (bp + 1)

Upvotes: 0

billz
billz

Reputation: 45410

you meant to write compare operator ==

if (bp1 == 1)
if (bp1 == 2)
//      ^^

if (bp1=1) will always be evaluated to true from operator=

Upvotes: 2

Kenneth McKanders
Kenneth McKanders

Reputation: 122

Welcome to the world of C++! You're definitely on the right track, but there a couple of problems. First, the operator you use in your if statements is the assignment operator, so your statements will always return true. This should actually be the comparison operator (==). Second, I recommend the use of an if-else if statement here, as you may not need to check both times. The following should be sufficient:

if(bp1 == 1)
{
    num = num * 2;
}
else if(bp1 == 2)
{
    num = num * 3;
}

Upvotes: 2

Sigar Dave
Sigar Dave

Reputation: 2654

There is a problem in your if statement

it must be like this :

if (bp1 == 1)
num = num*2;
if (bp1 == 2)
num = num*3;

Upvotes: 2

Related Questions