开发者

error with io stream

开发者 https://www.devze.com 2022-12-26 16:46 出处:网络
What is the problem with the last two statements in the code? #include <iostream> using namespace std;

What is the problem with the last two statements in the code?

#include <iostream>
using namespace std;
int main()
{
cout << "2 + 4 = " << 2 + 4 << endl;
cout << "2 * 4 = " << 2 * 4 << endl;
cout << "2 | 4 = " << 2 | 4 <<开发者_如何学JAVA; endl;
cout << "2 & 4 = " << 2 & 4 << endl;

What should I do to fix this?


What is the problem with the last two statements in the code?

Operator precedence. | and & have lower precedence than <<, so cout << "2 & 4 = " << 2 & 4 << endl; gets parsed as (cout << "2 & 4 = " << 2) & (4 << endl;).

What should I do to fix this?

Put parens around 2 | 4 and 2 & 4.


Put the expression in parentheses. The << operator is taking precedence over the bitwise operators.

#include <iostream>
using namespace std;
int main()
{
  cout << "2 + 4 = " << 2 + 4 << endl;
  cout << "2 * 4 = " << 2 * 4 << endl;
  cout << "2 | 4 = " << (2 | 4) << endl;
  cout << "2 & 4 = " << (2 & 4) << endl;
  return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号