Programming Question?

2019-10-03 10:05 pm
Given that x = 2, y = 1, z = 0, what will the following cout statement display?
cout << "answer = " << (x || !y && z) << endl;

Why would the answer be 1?

回答 (4)

2019-10-04 12:59 am
If you really want to learn C++ programming, or programming in any language, I suggest getting into the habit of writing code to see *what* happens. Then, if you can't work out the *why* of it after seeing the output (or if you're unsure of your conclusion) then ask.

It should take just a couple of minutes to fire up an IDE, type in a #include/using preamble and a main function to test this out.

Jack's final answer is correct if the statement is the first or only output done by the program. If other operations have been done on cout, then maybe not.

The logical operators (||, &&, !) will treat a numeric zero value or a nullptr pointer value as (false), and any other value as (true). The result of that expression is a bool (true) value. The order of operations rules evaluate ! first, then && and then ||, as if you had entered: (x || ((!y) && z)). Since x is nonzero (true), the values of y and z don't matter. (true || (anything)) will return true. In fact, the language guarantees that the right side of an || operator will not even be evaluated if the left side is (true).

The std::cout stream by default will display bool values as "0" for false and "1" for true; but you can change that using a standard output manipulator std::boolalpha.

To see how that works, type in and run the following program:

#include <iostream>

int main()
{
using namespace std;

int x = 2, y = 1, z = 0;
cout << "before boolalpha: answer = " << (x || !y && z) << endl;

cout << boolalpha;
cout << "after boolalpha: answer = " << (x || !y && z) << endl;

return 0;
}

My run of that produced the output:

before boolalpha: answer = 1
after boolalpha: answer = true
2019-10-03 10:39 pm
x=2 how..
ans is x=2
!y and z=!y and 0 = 0
ie 2 or 0=2(high)
it should be 1
2019-10-04 11:16 pm
The answer will always be 1.

1 means true.
since your cout-ing a condition and the condition is always true, so the condition is always 1.

simplest example is if you move your condition to an if statement, like so.
if (x || !y && z) {    cout << "true\n";}else{    cout << "false\n";}

even if you change any number from x, y or z it will be true! because of your condition. if you put a comparison in your condition then the event might change, such as if(x < z || !y= 0 && z). you see i have put some operators to lookout for comparisons.

Hope you understand.
2019-10-03 10:13 pm
How can x=2 on a logic problem?

2 ∨ (0 ∧ 0)


收錄日期: 2021-04-24 07:39:18
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20191003140529AAfoLEg

檢視 Wayback Machine 備份