【问题标题】:invalid operands of types 'int' and 'const char [11]' to binary 'operator<<''int' 和 'const char [11]' 类型的无效操作数到二进制 'operator<<'
【发布时间】:2023-03-21 10:00:01
【问题描述】:

首先,我只是一个初学者,如果这听起来很愚蠢,我很抱歉。

我目前正在用 C++ 做一个游戏,其中玩家的一举一动都对应着额外的金钱和时间扣除。每个玩家以 0 初始资金和 30 分钟的时间开始。我打算让这个循环直到两个玩家都剩下 0 时间。

这是我的代码的一部分:

if ((groupNumber1 == 1))
{
    cout<<"You now have a total of "<<"$"<< initialMoney += teensMoney <<" and have "<< initialTime -= teensTime <<" minutes remaining."<<endl;
}
else if ((groupNumber1 == 2))
{
    cout<<"You now have a total of "<<"$"<< initialMoney += familyMoney <<" and have "<<initialTime -= familyTime <<" minutes remaining."<<endl;  
}

现在当我运行程序时,它给了我这个:

[错误] 'int' 和 'const char [11]' 类型的无效操作数到二进制 'operator

我可以知道错误在哪里吗? 非常感谢!

【问题讨论】:

  • 看起来像一个优先级问题。 += 将在 &lt;&lt; 之后出现。放置一些括号应该可以解决问题。但是你想在输出语句中 += 吗?
  • initialMoney += teensMoney --> ( initialMoney += teensMoney )initialTime -= teensTime --> ( initialTime -= teensTime )。基本上,只要把它放在括号里。

标签: c++ char integer constants operands


【解决方案1】:

看起来像一个优先级问题。 += 将在 之后出现

initialMoney += teensMoney --> ( initialMoney += teensMoney )

【讨论】:

    【解决方案2】:

    由于运算符优先规则(&lt;&lt;+=-= 之前计算),您需要将算术表达式括起来,如下所示:

    if ((groupNumber1 == 1))
    {
        cout<<"You now have a total of "<<"$"<< (initialMoney += teensMoney) <<" and have "<< (initialTime -= teensTime) <<" minutes remaining."<<endl;
    }
    else if ((groupNumber1 == 2))
    {
        cout<<"You now have a total of "<<"$"<< (initialMoney += familyMoney) <<" and have "<<(initialTime -= familyTime) <<" minutes remaining."<<endl;  
    }
    

    【讨论】:

      【解决方案3】:

      呼应@user4581301 的观点 - 你确定你想在这里使用+=-= 吗?这将在打印输出后永久更改存储在这些变量中的值,我怀疑这是您想要做的。这也不会打印出正确的值 - 你明白为什么吗?

      相反,只需使用老式的+-

      if (groupNumber1 == 1)
      {
          cout << "You now have a total of " << "$" << initialMoney + teensMoney << " and have " << initialTime - teensTime << " minutes remaining." << endl;
      }
      else if (groupNumber1 == 2)
      {
          cout << "You now have a total of " << "$" << initialMoney + familyMoney << " and have " << initialTime - familyTime << " minutes remaining." << endl;  
      }
      

      【讨论】:

        【解决方案4】:

        简化问题以减少我们得到的噪音

        cout << a += b << endl;
        

        由于operator precedence,编译器将其解释为

        (cout << a) += (b << endl);
        

        b &lt;&lt; endl 舞台毫无意义。你可以通过用括号强制你想要的顺序来解决这个问题

        cout << (a += b) << endl;
        

        但我发现修改输出语句中的值会导致编程错误,因为即使您打算将a 更新为+=,人们也希望输出语句中的值不会发生变化。如果你真的想更新a 的值,我会用

        消除所有歧义
        a+=b;
        cout << a << endl;
        

        如果你不想更新a

        cout << a + b << endl;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-30
          • 1970-01-01
          • 1970-01-01
          • 2020-06-23
          • 1970-01-01
          • 2014-07-19
          相关资源
          最近更新 更多