vendredi 1 février 2019

How do I fix this code so that it doesnt flag up a 'System.OutOfRangeException' error? [duplicate]

I'm currently creating a binary calculator using simple for loops. I'm not sure how to set the size of my array so that it doesnt show up with this error.

This is for a school project and I have tried changing the order that the arrays are set.

int arrayLengths = int.Parse(Console.ReadLine()); // user input
carry = new int[arrayLengths + 1]; 
result = new int[arrayLengths + 1];


for (int i = firstBinaryNumber.Length - 1; i >= 0; i--)
            {

if (firstBinaryNumber[i] == 0 && secondBinaryNumber[i] == 0 && carry[i] == 0)
                    {
                        carry[i - 1] = 0;
                        result[i] = 0;
                    }

if (firstBinaryNumber[i] == 0 && secondBinaryNumber[i] == 0 && carry[i] == 1)
                    {
                        carry[i - 1] = 0;
                        result[i] = 1;
                    }


if (firstBinaryNumber[i] == 0 && secondBinaryNumber[i] == 1 && carry[i] == 0)
                    {
                        carry[i - 1] = 0;
                        result[i] = 1;
                    }


if (firstBinaryNumber[i] == 0 && secondBinaryNumber[i] == 1 && carry[i] == 1)
                    {
                        carry[i - 1] = 1;
                        result[i] = 0;
                    }


if (firstBinaryNumber[i] == 1 && secondBinaryNumber[i] == 0 && carry[i] == 0)
                    {
                        carry[i - 1] = 0;
                        result[i] = 1;
                    }


if (firstBinaryNumber[i] == 1 && secondBinaryNumber[i] == 0 && carry[i] == 1)
                    {
                        carry[i - 1] = 1;
                        result[i] = 0;
                    }


if (firstBinaryNumber[i] == 0 && secondBinaryNumber[i] == 1 && carry[i] == 0)
                    {
                        carry[i - 1] = 0;
                        result[i] = 1;
                    }


if (firstBinaryNumber[i] == 1 && secondBinaryNumber[i] == 1 && carry[i] == 0)
                    {
                        carry[i - 1] = 1;
                        result[i] = 0;
                    }


if (firstBinaryNumber[i] == 1 && secondBinaryNumber[i] == 1 && carry[i] == 1)
                    {
                        carry[i - 1] = 1;
                        result[i] = 1;
                    }
                } 

What I need is for this error to stop flagging up and for the carry and result arrays to show the correct numbers.

Aucun commentaire:

Enregistrer un commentaire