0

So i entered this code

static void Main(string[] args)
{
    int y = Console.Read();
    Program program = new Program();
    program.Prime(y);
}

public void Prime(int Value)
{
    Console.WriteLine(Value);
}

and when i enter a value, what prints out is the value I entered + 48. So if I enter 3, 'Console.WriteLine' prints out 51. Please help. I thought it was from my laptop so i restarted it but still no luck.

Alex Sikilinda
  • 2,928
  • 18
  • 34
Chi Chi
  • 9
  • 1

2 Answers2

1

You want

Console.ReadLine();

Read is the next character

Ryan Schlueter
  • 2,223
  • 2
  • 13
  • 19
1

Because the ascii code for

'0' is 48
'1' is 49
.
.
.
'9' is 57

If you enter 1 for example, it is not actually number 1, but '1' (character with ascii code of 49) and parsing it as int would give you 49. You could do this to get the desired result:

int y = Console.Read() - '0';

However if you want to read numbers more than 9 (more than one digit) this ain't gonna work, it is better that you parse it to int:

int y = int.Parse(Console.ReadLine();

Or even to make sure that entered value is parseable to int:

int y = 0;
while(!int.TryParse(Console.ReadLine(), y);
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171