I'm trying to do a simple math problem, but I keep getting this error message. What is wrong? I'm using cloud9 ide.
/home/ubuntu/workspace/Sphere.cpp: In function 'int main()': /home/ubuntu/workspace/Sphere.cpp:20:63: error: invalid operands of types 'int' and 'const char [15]' to binary 'operator<<' cout << "The area of the circle is: " << 3.14*meters^2 << "meters squared" << endl;
Here is the entire code:
#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;
}
In C++, the ^
operator does not mean exponentiation. It means to do a bitwise-XOR operation on two integer values.
And since ^
has lower precedence than <<
, the compiler interprets your statement as
((cout << "The area of the circle is: ") << (3.14*meters)) ^
((2 << "meters squared") << endl);
and gets hung up on what 2 << "meters squared"
is supposed to do.
In general, C++ has std::pow
for exponentiation. But it's overkill for just squaring a number, and it's probably better to just multiply that number by itself:
std::cout << "The area of the circles is: " << 3.14*meters*meters
<< " meters squared" << std::endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.