Home > Enterprise >  Why does it say that there's a casting error
Why does it say that there's a casting error

Time:07-05

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

CodePudding user response:

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.

CodePudding user response:

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);
     }
  •  Tags:  
  • c#
  • Related