none
I wonder Integer representation RRS feed

  • Question

  • using System;
    
    class Driver
    {
        static void Main()
        { 
            int guess = 0;
            Console.WriteLine ( "\nBefore guess: {0}", guess);
            Console.WriteLine("0 or 1 ?");
            guess = Console.Read();
            Console.WriteLine ( "\nAfter guess: {0}", guess);
            
        }
    }

    The output  in console when I pressed 0(zero):
    Before guess: 0
    0 or 1 ?
    0
    After guess: 48


    from where the heck comes 48? Meaning of life or something? (In some novel it was 42) :)

    • Edited by Ocellata Sunday, June 17, 2018 12:45 PM
    Sunday, June 17, 2018 12:42 PM

All replies

  • 48 is the ASCII value
    Sunday, June 17, 2018 1:28 PM
  • Take a look at the example code at Console.Read Method

    It converts the value returned by Console.Read() to its character representation.

    IIRC, the novel was "The Hitchhiker's Guide to the Galaxy". :)


    • Edited by RLWA32 Sunday, June 17, 2018 2:24 PM
    Sunday, June 17, 2018 1:58 PM
  • Both of the replies are correct, but I don't think they're really telling the whole story for a beginner.

    Console.Read returns the ASCII value of the next character typed at the keyboard.  The ASCII value of the character '0' is 48 in decimal.  If you want to assume that the user will always enter a digit, you can say:

        guess = Console.Read() - '0';

    but it's probably better to say something like:

        if( guess == '0' )


    Tim Roberts, Driver MVP Providenza & Boekelheide, Inc.

    • Proposed as answer by Dolen Zhang Tuesday, June 19, 2018 8:59 AM
    Monday, June 18, 2018 3:56 PM