how to use a variable outside of an if statement that is already declared inside an if statement

a 夏天 提交于 2021-01-27 18:55:04

问题


hey guys im just learning C# in school and am having trouble figuring out how i can use a variable outside of an if statement when that variable is already declared inside an if statement..heres what my program looks like........i have to use the "factor" variable outside of the if statemants because it is part of an equation that i need for a school assignment..if i am missing anything or you need more information, plz dont hesitate to tell me

 public caloriesCalculator()
        {
            InitializeComponent();
        }

        private void calculate_Click(object sender, EventArgs e)
        {
            double kilos;
            double pounds;
            int factor;
            double totalcalories;
            pounds = double.Parse(lbsTxt.Text);
            kilos = pounds * 0.45;
            kilosTxt.Text = kilos.ToString();


            {

                if (maleRadio.Checked && activeRadio.Checked)
                {
                    factor = 15;
                }

                if (femaleRadio.Checked && activeRadio.Checked)
                {
                    factor = 12;
                }

                if (maleRadio.Checked && inactiveRadio.Checked)
                {
                    factor = 13;
                }

                if (femaleRadio.Checked && inactiveRadio.Checked)
                {
                    factor = 10;
                }
            }
        }

回答1:


Not clear: But are you saying that this doesn't compile? You need to assign a value (a default) before going inside the if statement.

int factor = 15;



回答2:


You do need to initialize your variables, but if you want to return a number you need to do it with an int type. Void means return nothing. Try using an int method to do this, and return the variable.

I.E. private int radioChecker()

if(this happens) {
factor = 15;
return factor;
}

etc etc

then place radioChecker() inside your void and you can have different things happen based on what it returns.



来源:https://stackoverflow.com/questions/19350695/how-to-use-a-variable-outside-of-an-if-statement-that-is-already-declared-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!