首页 > 解决方案 > 'int' 和 'const char [15]' 类型的无效操作数到二进制 'operator<<' ^

问题描述

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

/home/ubuntu/workspace/Sphere.cpp:在函数“int main()”中:/home/ubuntu/workspace/Sphere.cpp:20:63:错误:“int”和“const char”类型的无效操作数 [15 ]' to binary 'operator<<' cout << "圆的面积是:" << 3.14*meters^2 << "平方米" << endl;

这是整个代码:

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

}

标签: c++

解决方案


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

并且由于优先级^低于,编译器将您的语句解释为<<

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

并被挂断了2 << "meters squared"应该做的事情。

通常,C++ 具有std::pow求幂功能。但是仅仅对一个数字求平方就有点过分了,最好只用这个数字乘以它自己:

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

推荐阅读