M
M
Michael2018-12-24 23:15:03
C++ / C#
Michael, 2018-12-24 23:15:03

How to get the square of a number and print it to the console?

Following code

using System;

namespace test3
{
    class Program
    {
        public static void Main()
        {
            Print(GetSquare(42));
        }
        static int GetSquare(double number)
        {
            number = (int)Math.Round(number);
            return Math.Pow(number, 2);
        }

        static void Print(int v)
        {
            Console.WriteLine();
        }
    }
}

Should find the square of the number (42) and output it to the console.
I'm learning C# for about... 4 hours. And for me it turned out to be a problem.
The debugger complains: Unable to convert type double to int. Perhaps a typecast was missed.
Googled it. Found a solution a la: In my case, this did not solve the problem. Krch help guys. Ay nid help.
num = (int)Math.Round(num);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Bashinsky, 2018-12-25
@BashkaMen

Better do that :)
static int GetSquare(int number)
{
return number * number;
}

G
GavriKos, 2018-12-24
@GavriKos

1) Never overwrite a function argument variable. Those. like this:
number = (int)Math.Round(number);
do not do it. Get a new variable
2) Based on the first point - what data type will this variable have?
3) Look at what Math.Pow accepts and returns.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question