-1

The prob is: "Read 2 variables, named A and B and make the sum of these two variables, assigning its result to the variable X. Print X as shown below. Print endline after the result otherwise you will get “Presentation Error”."

int A =  Console.Read();
int B =  Console.Read();
int C = A + B;

Console.WriteLine("X = " + C + "\n");

I Thought it was as simple as that(cos in c++ is). I am ultimately wrong.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 2
    The input from a console is a string, you have to convert the input to an int: `int A = Convert.ToInt32(Console.ReadLine());` – EpicKip Oct 03 '18 at 11:10
  • 1
    Console.ReadLine(); gives you string, convert it to int – Gopesh Sharma Oct 03 '18 at 11:10
  • You are reading in strings. If you don't Parse (TryParse) them to numbers then you are not doing a numeric sum but string concat. – Cetin Basoz Oct 03 '18 at 11:11
  • Do i always have to do Convert when i expect to have an input besides a string? – Igor Cherkasov Oct 03 '18 at 11:13
  • @IgorCherkasov I you want something to be a number and it is not you will have to Parse/Convert yes – EpicKip Oct 03 '18 at 11:13
  • 1
    FYI even though `Console.Read` returns an `int` it's not what you want. It's basically giving you the Ascii value of a single character. As mentioned by others you'll want to use `Console.ReadLine` to get the input then parse that to an `int`. – juharr Oct 03 '18 at 11:20

2 Answers2

0

You shoud convert the string that Console.ReadLine() retrieve from the keyboard in order to have ints:

int A =  Int32.Parse(Console.ReadLine());
int B =  Int32.Parse(Console.ReadLine());
int C = A + B;

Console.WriteLine("X = " + C + "\n");

Here is the working example of this code: working code

clement
  • 4,204
  • 10
  • 65
  • 133
  • You could also make a direct Console.WriteLine("X = " + A + B + "\n"); – clement Oct 03 '18 at 11:20
  • This looks right, not sure why you're getting downvoted – ShamPooSham Oct 03 '18 at 11:22
  • @ShamPooSham: the man that made other answer juste after me was not fair play and wanted to be first so he downvoted in order to be first with neutral score ;-) He finally deleted his answer and let mine with -1 :-) – clement Oct 03 '18 at 11:28
-3

Console.ReadLine() returns a string. You have to convert it to an int

int Number = Convert.ToInt32(Console.ReadLine());

And I'm not sure how Console.WriteLine() handles numbers, but just to be sure do

Console.WriteLine("X = " + C.ToString() + "\n");

EDIT Just checked it out, Console.WriteLine() automatically calls the objects .ToString() method if it is not a string, therefore

Console.WriteLine("X = " + C + "\n");

is okay

Shmosi
  • 322
  • 2
  • 17
  • The string concatenation will automatically call `ToString` as would `Console.WriteLine` if you pass it something other than a `string`. – juharr Oct 03 '18 at 11:17
  • Just checked that out too and updated my answer – Shmosi Oct 03 '18 at 11:18