Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, I am new to C++ even to this website and I was trying to make a console calculator with arithmetic operators and some bitwise operators too.
So everyone knows 2 << 4 = 32.
But when I run the following code:

C++
cout << 2 << 4 << endl;



It gives me 24 not 32.
Why is that


And if you want to see my overall code find it below:

#include <iostream>

using namespace std;

int main() {

  int a, b;
  char o;
  string l = "Answer is: ";
  cout << "Enter First Number: ";
  cin >> a;

  cout << "Enter Second Number: ";
  cin >> b;

  cout << "\nEnter Operation: ";
  cin >> o;

  if (o == '+') 

    cout << l << a + b << endl;
  else if (o == '-')
    cout << l << a - b << endl;

  else if (o == '*') 
    cout << l << a * b << endl;
  
  else if (o == '/') 
    cout << l << a / b << endl;
  
  else if (o == '%')
    cout << l << a % b << endl;

  else if (o == '<') 
    cout << l << 2 << 4 << endl;
  return 0;

}


The code is not very clean, I know
and if you are wondering about the {} it doesn't matter because I tried other simple operator like + or *

What I have tried:

I have tried removing the
C++
endl
Posted
Updated 27-Jan-21 22:05pm

 
Share this answer
 
Comments
CPallini 28-Jan-21 6:02am    
5.
Quote:
C++
cout << 2 << 4 << endl;

It gives me 24 not 32.
Why is that

Because << is a bitwise operator and an output separator depending if in a cout or not.
Note you have the same with cin and >>.
to get 32, you need to
C++
cout << (2 << 4) << endl;
 
Share this answer
 
Comments
CPallini 28-Jan-21 6:02am    
5.
Patrice T 28-Jan-21 6:24am    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900