What's the answer for this code in c++ & c#and why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What's the answer for this code in c++ & c#and why?

int a,b; a=-5; b=2; if(a/b) {cout<<"True";} else {cout<<"False";}

23rd Nov 2016, 6:44 PM
Rohit Pandey
Rohit Pandey - avatar
6 Answers
+ 4
The answer must be False for both the languages. As anything other than 0 is true and 0 is False. 2/-5=-0.4 But since data type is int only 0 that is the integral part of the number will be stored. So a/b = 0 i.e. false. So the else part gets executed to output false.
24th Nov 2016, 12:55 AM
Megatron
Megatron - avatar
+ 3
yes. any number except 0 integer +ve or -ve floating double all are true except 0.
24th Nov 2016, 1:00 PM
Megatron
Megatron - avatar
+ 2
thanks for the help brother!
24th Nov 2016, 1:23 PM
Rohit Pandey
Rohit Pandey - avatar
+ 2
that means all the numbers except 0 are treated as true @David-Hesh Hochhauser
24th Nov 2016, 6:04 PM
Rohit Pandey
Rohit Pandey - avatar
+ 1
does it works for negative values too?
24th Nov 2016, 12:53 PM
Rohit Pandey
Rohit Pandey - avatar
0
Megatron has it almost right. But his numbers are backwards. -5 / 2 as integer = -2. which is True because -2 is not 0. This is because of how numbers are stored in binary. All non-zero values (even negative ones) have at least one bit set in their binary representation. So any non-zero value, Int or float, is considered True. However, in C you can evaluate an integer by its individual bits. For example: 3 && 4 = True and True = True but single & is bitwise in binary 3 & 4 = 011 and 100 bit by bit = 000 = False
24th Nov 2016, 5:29 PM
David-Hesh Hochhauser
David-Hesh Hochhauser - avatar