【问题标题】:invalid operands of types ‘int’ and ‘const char [15]’ to binary ‘operator<<’ ^“int”和“const char [15]”类型的无效操作数到二进制“operator<<”^
【发布时间】:2018-08-28 02:20:30
【问题描述】:

我正在尝试做一个简单的数学问题,但我不断收到此错误消息。怎么了?我正在使用cloud9 ide。

/home/ubuntu/workspace/Sphere.cpp:在函数“int main()”中: /home/ubuntu/workspace/Sphere.cpp:20:63:错误:无效的操作数 将“int”和“const char [15]”类型转换为二进制“operator

这是完整的代码:

#include <iostream>

using namespace std;

int main() {

    // Declare the radius
    int meters;
    cout << "Please enter the radius in meters: ";
    cin >> meters;

    // Calculate Diameter

    cout << "The diameter of the circle is: " << meters*2 << "m" << endl;

    //Calculate Area
    double PI;
    PI = 3.14;

    cout << "The area of the circle is: " << 3.14*meters^2 << "meters squared" << endl;

}

【问题讨论】:

  • 切换 >> 和
  • ^ 不是你想的那样。
  • 3.14*meters*meters
  • 附注:你可以考虑写PI = 4.0 * atan(1.0)并使用#include &lt;math.h&gt;

标签: c++


【解决方案1】:

在 C++ 中,^ 运算符 not 表示求幂。这意味着对两个整数值进行按位异或运算。

由于^precedence 低于&lt;&lt;,编译器会将您的语句解释为

((cout << "The area of the circle is: ") << (3.14*meters)) ^
    ((2 << "meters squared") << endl);

然后对2 &lt;&lt; "meters squared" 应该做什么感到困惑。

一般来说,C++ 有std::pow 用于求幂。但是仅仅对一个数字进行平方就有点过分了,最好将这个数字乘以它自己:

std::cout << "The area of the circles is: " << 3.14*meters*meters 
          << " meters squared" << std::endl;

【讨论】:

  • std::pow 用于浮点取幂,由于舍入错误,我不建议在任何情况下将其用于整数
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 1970-01-01
  • 2014-07-19
相关资源
最近更新 更多