使用if语句时,该名称在当前上下文中不存在 [英] The name does not exist in the current context when using an if statement

查看:61
本文介绍了使用if语句时,该名称在当前上下文中不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用用户给定的小数位数计算Pi,并且当输入为0时,变量piNumber应该设置为'3'而不是'3',这样输出就不会没有用处逗号.

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.

这有效

        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;
    }

但是使用if语句则不会

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
    }

对于上面代码中所指向的行,我两次收到错误消息名称'piNumber'在当前上下文中不存在"

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

推荐答案

您在 if 语句中声明并为 piNumber 变量分配了一个值,因此它不可用在此范围之外.尝试在 if

You declare and assign a value to piNumber variable inside if statement, therefore it isn't available outside this scope. Try to declare it before if

string piNumber;
if (amountOfDigits == 0)
{
    piNumber = "3";
}
else
{
    piNumber = "3,";
}

这篇关于使用if语句时,该名称在当前上下文中不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆