Solving C++ Logical Ops 2: Print "Special Number

  • C/C++
  • Thread starter ineedhelpnow
  • Start date
  • Tags
    C++
In summary, the correct expression to print "Special number" if specialNum is -99, 0, or 44 is (specialNum == -99) || (specialNum == 0) || (specialNum == 44). Using a single equals sign instead of double will result in the statement being true and always outputting "special number". It is important to pay attention to the difference between = and == in conditional statements.
  • #1
ineedhelpnow
651
0
Write an expression that prints "Special number" if specialNum is -99, 0, or 44.

Sample program:

Code:
#include <iostream>
using namespace std;

int main() {
   int specialNum = 0;

   specialNum = 17;
   
   if (<STUDENT CODE>) {
      cout << "Special number" << endl;
   }
   else {
      cout << "Not special number" << endl;
   }

   return 0;
}

i thought it would be
Code:
(specialNum == -99) || (specialNum == 0) || (specialNum = 44)
but its not
 
Technology news on Phys.org
  • #2
ineedhelpnow said:
Write an expression that prints "Special number" if specialNum is -99, 0, or 44.

Sample program:

Code:
#include <iostream>
using namespace std;

int main() {
   int specialNum = 0;

   specialNum = 17;
   
   if (<STUDENT CODE>) {
      cout << "Special number" << endl;
   }
   else {
      cout << "Not special number" << endl;
   }

   return 0;
}

i thought it would be
Code:
(specialNum == -99) || (specialNum == 0) || (specialNum = 44)
but its not

That last condition is an assignment. You want specialNum == 44, because "specialNum = 44" is a statement that means "assign 44 to specialNum, and return that value". Thus it logically becomes true (as 44 is not zero) and you always get "special number" (and if you printed specialNum it would mysteriously always be 44.

Be careful between = and == :)
 
  • #3
i literally read over that piece of code i wrote like ten times and i didnt even notice that i missed a '='. thanks bacterius!
 

Similar threads

Replies
5
Views
2K
Replies
22
Views
3K
Replies
40
Views
3K
Replies
6
Views
10K
Replies
23
Views
2K
Replies
13
Views
1K
Back
Top