I am trying to make a simple calculator for my code and I wanted to know, how can I have the user input a number like c++ cin >> number; and then just have my math functions do the rest. I have this so far...

``````public static void Main()
{
int x, y, result;
float floatresult;

result = x + y;
Console.WriteLine("x + y : {0}", result);

}``````

The int x = Console.ReadLine() is red. Can anyone help me out???

Input from the console is a string, so you'll have to accept it as one and then convert it.

``````int x;
if (Int32.TryParse(input, out x)) {
// x can be converted to a number, do whatever you need to do here
} else …``````
``````int x, y, result;

Console.WriteLine("Enter x: ");

Console.WriteLine("Enter y : ");

result = x + y;

Console.WriteLine("{0} + {1} = {2}", x, y, result);
``````

mark as solved, if this satisfies your requirement.

All 6 Replies

Input from the console is a string, so you'll have to accept it as one and then convert it.

``````int x;
if (Int32.TryParse(input, out x)) {
// x can be converted to a number, do whatever you need to do here
} else {
// x can't be converted to a number
}``````
commented: Thank You for helping me. +0
``````int x, y, result;

Console.WriteLine("Enter x: ");

Console.WriteLine("Enter y : ");

result = x + y;

Console.WriteLine("{0} + {1} = {2}", x, y, result);
``````

mark as solved, if this satisfies your requirement.

Thank You for helping me. This is my finished code. What do you think????

``````using System;

class program
{
public static void Main()
{
int x, y, result;
float floatresult;
Console.Write("What is the X Value? ");
Console.WriteLine(" ");
Console.Write("What is the Y Value? ");
Console.WriteLine(" ");
if (Int32.TryParse(xnumberinput, out x) && Int32.TryParse(ynumberinput, out y))
{
result = x + y;
Console.WriteLine("x + y : {0}", result);
Console.WriteLine(" ");
result = x - y;
Console.WriteLine("x - y : {0}", result);
Console.WriteLine(" ");
result = x * y;
Console.WriteLine("x * y : {0}", result);
Console.WriteLine(" ");
result = x / y;
Console.WriteLine("x / y : {0}", result);
Console.WriteLine(" ");
floatresult = (float)x / (float)y;
Console.WriteLine("This uses x and y as floaters. x / y: {0}", floatresult);
Console.WriteLine(" ");
result = x % y;
Console.WriteLine("x % y : {0}", result);
Console.WriteLine(" ");
result += x;
Console.WriteLine("Result += x: {0}", result);
}
else
{
Console.WriteLine("Not Doable");
}
Console.WriteLine(" ");
Console.WriteLine("Press Enter To Exit The Program. ");