0

对不起这个问题,这是我的第一个 C++ 项目,我有点困惑。我要求用户输入 3 个单独的内容。例如,我从一个数字 80 开始。我要问用户 3 个问题。1)你喜欢蓝色还是黄色?输入 1 表示蓝色,输入 2 表示黄色。如果用户为蓝色输入 1,则将数字 80 乘以 2。如果他们为黄色输入 2,则将 80 乘以 3。

有人可以告诉我这看起来是否在正确的轨道上吗?再次感谢并为初学者的问题感到抱歉。

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;
4

4 回答 4

2

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;
}
于 2014-03-11T06:09:41.773 回答
2

你的意思是写比较运算符==

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

if (bp1=1)将始终从operator=

于 2014-03-11T06:02:12.213 回答
2

你的 if 语句有问题

它必须是这样的:

if (bp1 == 1)
num = num*2;
if (bp1 == 2)
num = num*3;
于 2014-03-11T06:02:55.540 回答
0

更简单:

代替:

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

你可以写这个

  num = num * (bp + 1)

甚至

  num *= (bp + 1)
于 2014-03-11T07:57:13.710 回答