简体   繁体   English

if语句中的平等比较

[英]Equality comparison in if-statement

Sorry about this question, this is my first C++ project and I'm a little confused. 抱歉这个问题,这是我的第一个C ++项目,我有些困惑。 I'm asking the user to input 3 separate things. 我要用户输入3个单独的东西。 For example, I'm starting off with a number, 80. I'm asking the user 3 questions. 例如,我从80开始。我问用户3个问题。 1) Do you like blue or yellow? 1)你喜欢蓝色还是黄色? Type 1 for blue, 2 for yellow. 键入1代表蓝色,2代表黄色。 If the user enters 1 for blue, multiply the number 80 by 2. If they enter 2 for yellow, multiply 80 by 3. 如果用户输入1表示蓝色,则将数字80乘以2。如果用户输入2表示黄色,则将80乘以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;

you meant to write compare operator == 你打算写比较运算符==

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

if (bp1=1) will always be evaluated to true from operator= if (bp1=1)始终会被operator=评估为true

There is a problem in your if statement 您的if陈述式有问题

it must be like this : 它一定是这样的:

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

Welcome to the world of C++! 欢迎来到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. 首先,您在if语句中使用的运算符是赋值运算符,因此您的语句将始终返回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. 其次,我建议在此处使用if-else if语句,因为您可能不需要同时检查两次。 The following should be sufficient: 以下内容就足够了:

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM