+ 3
why this output is 4?
#include <iostream> using namespace std; int x=0; int y= --x; int main (){ if(++y +5) y*=5; y+=5; cout<<x+y; return 0;}
11 Respuestas
+ 4
Remember that any nonzero value in C is equivalent to a boolean condition of true.
+ 2
"if" treats right operations (that don't make errors) as True.
That way, x and y before if statement equal -1
In if statement y increases to 0
0*5=0, that way after "if" y stays as 0
0+5=5, so y is 5 now
-1+5=4, that's the output
+ 2
int x=0;
int y= --x; // decrement x, then assign its value to y => both x and y are - 1
int main (){
if(++y +5) // ++y changes y's value to 0, 0+5 = 5, 5 is true, so the following statement is executed
y*=5; // y=0*5 = 0
y+=5; // y=5
cout<<x+y; // 5+(-1) = 4
return 0;}
if(++y+5) isn't true because it doesn't cause any errors, but because it results in a positive number (which is equivalent to true). If the operation resulted in 0 (for example in if(++y*0)), it would be considered false.
So yes, the +5 part is important because without it, the statement would equal 0 and the condition would be false (then again, it doesn't matter in this specific case because all the if block does is multiply y with 5 which doesn't change its value because y is 0). The +5 in the if statement is not added to the value of y.
+ 1
The "+5" bit isn't actually changing the value of y. If you replace the if statements condition to:
"y = ++y + 5"
Then the result would be different (29)
+ 1
Again, operations without error is True in if
Aa LyTon said, y will change if you place "y=++y+5", which is still True in if statement
But without it, program just like "okay, i actually can do it, but this won't change anything"
It sometimes may make the program output wrong answer, when you forget that equality is "=="
+ 1
Well then that would evaluate to "0 > 5" so the if statement won't run.
I can't tell by the way the code is laid out but I'm assuming the "cout" and "return" statement are outside the if statement, so like this:
int x = 0;
int y = --x;
int main() {
if (++y > 5) {
y *= 5;
y += 5;
}
cout << x + y;
return 0;
}
So x and y would both be -1 and the output would be -2.
There's really no need for an else statement here since your really not doing anything else.
+ 1
Because firstly we have x, y=-1, then y=0, then also 0, after that y=0+5=5, cout << -1+5 -> so 4
0
if i delete '+5' in 'if(++y +5)' , the out put is 4 too , why ?
and if i change +5 to +6 or else, the output is 4 too, why?
0
so, '+5' isn't important and don't have other meaning? what happend if i change '+' to '>' ? , (++y > 5 ) , that can change the ouput or the program will be error?
why 'if' on that code not use 'else' ?
0
If(0+5)
{ y=0*5;
y=0+5;
cout<<-1+5
}
so the output is, 4
0
ok, thanks for the answer.