0

I have been given an assignment on C# window form where I get to calculate an input textbox from a user, the user wants to input a value and then presses a radiobutton(square root) then clicks a normal button to get the result. Is it possible to get the result in a textbox (instead of a label)? If so, how do I do that using 'methods' (linking methods to the button_click one)? Also, why do I need to return a parameter value of a method? it doesn't let me execute without returning ;/

{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private int square(int A)
        {
            if (rbSquare.Checked)
            {
                Math.Sqrt(A);
                return Convert.ToInt32(Math.Sqrt(A));
            }
            else
            {
                return A;
            }

        }
        private void btncalculate_Click(object sender, EventArgs e)
        {
            int firstNum = Convert.ToInt32(tbinput.Text);
            int squareRoot = square(firstNum);
            tbResult.Text = "" + squareRoot;

        }
    }
}
2
  • You should use (int)Math.Sqrt(A); rather than Convert.ToInt32; it is more idiomatic in C# to use a cast here. Mar 7, 2020 at 2:11
  • Why are you calling the square root function twice? Mar 7, 2020 at 2:12

1 Answer 1

0

Is it possible to get the result in a textbox (instead of a label)?

Sure. Set the text property of the text box, just like you would set the label text of a label.

why do I need to return a value from a method?

You said that square returns an int always, but you only return an int if the checkbox is checked. The compiler is reminding you that you need to return an int always in order to fulfill the contract that you promised. What value should you return if the checkbox is not checked?

6
  • Yes, logically square roots usually give you a whole number that you multiply by itself gives you that number to square root it. If I don't check the radiobutton not the checkbox, then I get no result
    – Oso
    Mar 6, 2020 at 23:36
  • or if i don't check the radiobutton, it will give me the value input itself without square rooting it
    – Oso
    Mar 6, 2020 at 23:38
  • ok I got the answer but I still didn't understand why return only accepts double numeric values and not integers
    – Oso
    Mar 6, 2020 at 23:45
  • @Oso: I don't understand your question. Your method is typed as returning int, so you must return an int, not a double. Mar 7, 2020 at 2:10
  • @Oso: Square roots do not give you a whole number; they give you a fraction. If you ask for the square root of 2, you get 1.414... not 1 or 2! Mar 7, 2020 at 2:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.