+ 2

why is this true? Very thankful for any help :)

int age; bool can_drink; Console.Write("Enter your age: "); age=Console.Read(); can_drink=(age>=21)? true:false; Console.Write(can_drink); input(3) Output: true :/

27th Jun 2017, 7:36 AM
Jared
Jared - avatar
12 Réponses
+ 5
I get it now, thank you both :)
27th Jun 2017, 7:57 AM
Jared
Jared - avatar
+ 4
Thank you all, especially Sachin! Why does the conversion affect the output?
27th Jun 2017, 7:53 AM
Jared
Jared - avatar
+ 4
To David, when I entered 22 it was still true. I even entered negative numbers, and it still evaluated to true. I tried Sachin's method, worked like a charm :), though I don't know why
27th Jun 2017, 7:56 AM
Jared
Jared - avatar
+ 3
There is, I was just playing around with ternary if :)
27th Jun 2017, 7:47 AM
Jared
Jared - avatar
+ 3
I somewhere read that, only the use of- Console.Read() ot Console.ReadLine() takes input as a string, but here you need integer, that's why I convert the input into integer using- Convert.ToInt32()
27th Jun 2017, 7:55 AM
Sachin Artani
Sachin Artani - avatar
+ 3
:)
27th Jun 2017, 7:57 AM
Sachin Artani
Sachin Artani - avatar
+ 2
Try this- int age; bool can_drink; Console.Write("Enter your age: "); age= Convert.ToInt32(Console.ReadLine()); can_drink=(age>=21)?true:false; Console.Write(can_drink);
27th Jun 2017, 7:51 AM
Sachin Artani
Sachin Artani - avatar
0
its there no sort of "if" statements for c#?
27th Jun 2017, 7:46 AM
D_Stark
D_Stark - avatar
0
oh... what happends if you input is 22?
27th Jun 2017, 7:48 AM
D_Stark
D_Stark - avatar
0
ok
27th Jun 2017, 4:35 PM
Zaw Hiaing Moe
Zaw Hiaing Moe - avatar
0
bro sinahtoowart Upright
27th Jun 2017, 4:35 PM
Zaw Hiaing Moe
Zaw Hiaing Moe - avatar
0
To all the people who are confused as to why that fixes the problem. I THINK it's because ReadLine() returns a string. So you have to convert/parse that string to get an int out of it.
30th Jun 2017, 9:44 AM
Pierre Gravelle
Pierre Gravelle - avatar