Hellcodes.js
Hellcodes.js

Reputation: 49

Why does it say that there's a casting error

I am pretty new to C# and I'm stuck with a problem in the code. Apparently, there is a casting error, can you tell me what is it?

Here's the code

public static void Main(string[] args)
{
    // side a and b
    Console.WriteLine("Side A of 90° triangle");
    double a = Convert.ToDouble(Console.ReadLine());

    Console.WriteLine("Side B");
    double b = Convert.ToDouble(Console.ReadLine());

    // c^2
    int csqr = (a * a) + (b * b);
    int hypo = Math.Sqrt(csqr);

    // hypo
    Console.WriteLine("hypotenuse:-  " + hypo);
}

Upvotes: 1

Views: 252

Answers (2)

NPE
NPE

Reputation: 28

You cannot put a double into an int. Variables hypo csqr must be double.

public static void Main(string[] args)
     {
       //side a and b
       Console.WriteLine("Side A of 90° triangle");
       double a = Convert.ToDouble(Console.ReadLine());
       Console.WriteLine("Side B");
       double b = Convert.ToDouble(Console.ReadLine());
       //c^2
       double csqr = (a * a) + (b * b);
       double hypo = Math.Sqrt(csqr);
       //hypo
       Console.WriteLine("hypotenuse:-  " + hypo);
     }

Upvotes: 1

Wael Moughrbel
Wael Moughrbel

Reputation: 244

The variables csqr and hypo should be of type double while you defined them as int. Sqrt is a method to find the square root. thus it takes a parameter of type double and returns double. sqrt documentation

csqr variable should be of type double because of the arithmetic operations on a double operands.

Upvotes: 2

Related Questions