samedi 18 avril 2020

The name does not exist in the current context when using an if statement [duplicate]

I want to calculate Pi with the number of decimal places given by the user and when the input is 0 the variable piNumber should be set to '3' and not '3,' so that the output doesn't have a useless comma.

This works

        static string PiNumberFinder(int amountOfDigits)
    {
        string piNumber = "3,";
        int dividedBy = 11080585;
        int divisor = 78256779;
        int result;
        for (int i = 0; i < amountOfDigits; i++)
        {
            if (dividedBy < divisor)
                dividedBy *= 10;

            result = dividedBy / divisor;

            string resultString = result.ToString();
            piNumber += resultString;

            dividedBy = dividedBy - divisor * result;
        }

        return piNumber;
    }

But with the if statement it doesn't

        static string PiNumberFinder(int amountOfDigits)
    {
        int dividedBy = 11080585;
        int divisor = 78256779;
        int result;
        if (amountOfDigits == 0)
        {
            string piNumber = "3";
        }
        else
        {
            string piNumber = "3,";
        }
        for (int i = 0; i < amountOfDigits; i++)
        {
            if (dividedBy < divisor)
                dividedBy *= 10;

            result = dividedBy / divisor;

            string resultString = result.ToString();
            piNumber += resultString;  // I get an error here

            dividedBy = dividedBy - divisor * result;
        }

        return piNumber;  // I get an error here
    }

I get the error "The name 'piNumber' does not exist in the current context" twice for the lines pointed in the code above

Aucun commentaire:

Enregistrer un commentaire