0

I made a calculator that works for small numbers but when the results get too large it returns NaN

List<string> memory = new List<string> { };

string display = "";
while (display.Contains("%") == false)
{
    string line = ReadLine();
    display = line;
    memory.Add(line);
}

float result = float.Parse(memory[0]);

for (int i = 1; i < memory.Count; i++)
{
    string temp = memory[i];
    char[] _temp = temp.ToCharArray();
    _temp = _temp.Where(x => x > _temp[0]).ToArray();
    float num = float.Parse(string.Join("", _temp));

    if (temp.Contains("+") == true) result += num;
    else if (temp.Contains("-") == true) result -= num;
    else if (temp.Contains("*") == true) result *= num;
    else if (temp.Contains("/") == true) result /= num;
    else if (temp.Contains("%") == true) result %= num;
}

Take these numbers for example:

797 * 2 + 38 * 212 * 275 * 806 * 67 * 9939 + 7 + 74 + 515 + 610 * 516 * 6921
+ 4 * 2 * 494 * 3153 * 8 + 2501 * 769 + 4 * 2472 + 1 * 21 * 6535 + 30 + 26
+ 44 + 240 + 88 * 1111 * 817 * 1576 + 551 * 535 + 9150 + 36 * 85 * 4598
* 9276 * 766 + 584 + 5 * 1 + 7 + 45 * 8152 % 7984

I enter each number in a new readline with the math symbol infront of it. If you test it with these numbers just be aware.

I've looked everywhere and cant figure out a solution to this problem so that it can return a real number.

Anyone know what I can do to fix this?

Jasen
  • 14,030
  • 3
  • 51
  • 68
Dominic
  • 19
  • 3
  • See http://stackoverflow.com/questions/4160988/c-sharp-unlimited-significant-decimal-digits-arbitrary-precision-without-java – JamesFaix Mar 28 '17 at 21:28
  • 1
    "797 * 2 + 38 * 212" given your parser, I think you're not considering associations - 797 * 2 should be resolved on one side, plus 38*212 in the other hand, and add those two values. I believe your calculator is reading from left to right and not considering that – Gonzalo.- Mar 28 '17 at 21:31

2 Answers2

1

The values you are using are too large for float. When the value gets too large for your float, it returns PositiveInfinity (or NegativeInfinity) instead of a number value. According to MSDN:

This constant is returned when the result of an operation is greater than MaxValue.

so your float becomes 'infinity' instead of a number.

Then, when you try an operation like divide or mod, float returns NaN. Again, from MSDN:

A method or operator returns NaN when the result of an operation is undefined.

so when you divide your float (infinity) by a number, the result is NaN

You may want to consider using BigInteger.

Izzy4Real
  • 41
  • 4
-1

The following limits apply:

  • Float: 7 digits (32 bit)
  • Double: 15-16 digits (64 bit)
  • Decimal: 28-29 significant digits (128 bit)
SLWS
  • 506
  • 4
  • 8