3

So i am just trying to get started with coding in general and i was trying to make a calculator in C# and it does work but i cant enter 0.4 problems or go higher than 9 numbers otherwise my calculator gives me this error: Value was either too large or too small for an Int32.

I searched the problem up and got led to this website and people here were talking about using a string instead. I tried that but it told me i cant use the - operator or * operator.

I am sorry that im even asking this there is probarly a super simple solution but i hope someone can answer this question.

class Program
{
    //Ints
    public static int value1;
    public static int value2;
    public static int result;
    public string input = Console.ReadLine();

    static void Main(string[] args)
    {
        while (true)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Choose your mathmetical operator:  (A)dd  (S)ubtract  (M)ultiply");
            if (Console.ReadLine() == "A")
            {
                Console.WriteLine("Enter 2 values.");
                value1 = Convert.ToInt32(Console.ReadLine());
                value2 = Convert.ToInt32(Console.ReadLine());
                Add(value1, value2);
            }
        }
    }

    static void Add(int value1, int value2)
    {
        result = value1 + value2;
        Console.WriteLine($"{result}");
        Console.ReadLine();
        Console.Clear();
        result = 0;
        value1 = 0;
        value2 = 0;
    }

    static void Subtract(int value1, int value2)
    {
        result = value1 - value2;
        Console.WriteLine($"{result}");
        Console.ReadLine();
        Console.Clear();
        result = 0;
        value1 = 0;
        value2 = 0;
    }

    static void Multiply(int value1, int value2)
    {
        result = value1 * value2;
        Console.WriteLine($"{result}");
        Console.ReadLine();
        Console.Clear();
        result = 0;
        value1 = 0;
        value2 = 0;
    }
}

}

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • 1
    Instead of `Convert.ToInt32()` use `Int32.TryParse()` to avoid issues when your input is not a valid `Int32`. If you need to work with fractional numbers, do not use `int`, use `double`. – Wiktor Stribiżew Mar 16 '17 at 11:09
  • if you store numbers in a string it's up to you to write the code that adds, subtracts, divides, multiplies according to the rules you learned in school. – Jason Lang Mar 16 '17 at 11:11
  • basic .Net types: https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx. Learn what are they and choose which suits you task best – ASh Mar 16 '17 at 11:11

3 Answers3

2

Your problem is that you are assigning the input to a Int32, which is an INTEGER number, meaning that 0.4 is not valid, also, integers have these limitations:

   Type      Capacity

   Int16 -- (-32,768 to +32,767)

   Int32 -- (-2,147,483,648 to +2,147,483,647)

   Int64 -- (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)

Taken from this answer.

If you want to continue to use integers, you may consider using Int64 instead. Otherwise you should probably use Double.

EDIT It seems that decimal is more suitable for calculators.

Community
  • 1
  • 1
Andre Pena
  • 56,650
  • 48
  • 196
  • 243
2

After analyzing your code all of the logic seems to be okay, but it looks like you don't have knowledge about data types. This is something you should start with and on this page you can read about built-in data types for C#.

Another thing you should know is how to change ( or convert ) data types. In your code you're expecting that user will follow your rules and input everything correctly. You have to treat your end user ( even yourself ) as a totally dumb person that will insert "number 6 please" in the field that is especially for numeric types. Simple example that will ask user for the generic input type can look like this :

public static TResult AskForInput<TResult>(string message)
{
    bool isValid = false;
    while(!isValid)
    {
        Console.WriteLine(message);
        string value = Console.ReadLine();
        try
        {   
            TResult result = (TResult)Convert.ChangeType(value, typeof(TResult));
            return result;
        }
        catch
        {
            Console.WriteLine("Input does not match requested type");
        }
    }
}

Last but I would say the most important thing is that you want user to input value with your predefined decimal mark ( . ) eg. 0.4. This decimal mark depends on the current culture information which is defined in : System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.

So for example you want to send this application to your friend within different country and in their culture they are using comma ( , ) decimal mark. Then your application can fail if you would like to parse this by yourself. Try to always check for this setting or include this in your conversion methods.

For your example I would suggest using double data type as it's commonly used in math operations. Combining this into your code can look somewhat similiar to this :

public static void Main(string[] args)
{
    //Your code goes here
    //while (true)
    {
        Console.WriteLine("Choose your mathmetical operator:  (A)dd  (S)ubtract  (M)ultiply");
        if (Console.ReadLine() == "A")
        {
            Console.WriteLine("Enter 2 values.");
            double value1 = AskForInput<double>("Enter left value :");
            double value2 = AskForInput<double>("Enter right value :");
            Add(value1, value2);
        }
    }
}

public static TResult AskForInput<TResult>(string message)
{
    bool isValid = false;
    TResult result = default(TResult);
    while(!isValid)
    {
        Console.WriteLine(message);
        string value = Console.ReadLine();
        try
        {   
            result = (TResult)Convert.ChangeType(value, typeof(TResult));
            isValid = true;
        }
        catch(Exception ex)
        {
            Console.WriteLine("Input does not match requested type");
        }
    }
    return result;
}

static void Add(double value1, double value2)
{
    double result = value1 + value2;
    Console.WriteLine(result);
}

static void Subtract(double value1, double value2)
{
    double result = value1 - value2;
    Console.WriteLine(result);
}

static void Multiply(double value1, double value2)
{
    double result = value1 * value2;
    Console.WriteLine(result);
}

Check this online

mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
1

As already said you should use Int64, Double or even Decimal. In addition to this, you have some other problems. Maybe these can be learning points:

  • You are not using the variable input, and very strangely you are initializing it to Console.ReadLine(), get rid of that.
  • While (true) is not a good loop condition. How do you intend to close the application?.
  • You are mixing business logic and presentation. Add, Multiply and Subtract should only do the calculation (business logic) and let the main loop do the presentation (Console.WriteLine()).
  • value1 and value2 are value parameters, they do not have any meaning outside the business logic functions, so there is no need to set them to 0 before returning.
  • +1 for using the $"{result}" format string.
Palle Due
  • 5,929
  • 4
  • 17
  • 32