Home > Back-end >  How do I ask for user input in C# in this code and I need a function to calculate the pythagorean
How do I ask for user input in C# in this code and I need a function to calculate the pythagorean

Time:06-13

I'm building a pythagoras calculator in c# for school, but I can't figure out how I should change the lines: s1 = 3; and s2 = 4; into lines that ask for user input. Not only that, I also need to use a function to calculate the pythagorean. Any help is appreciated because I'm totally lost, thank you!

using System;

public class Pythagorean {
  public static void Main() {
    double s1;
    double s2;
    double hypot;

    s1 = 3;
    s2 = 4;

    hypot = Math.Sqrt(s1*s1   s2*s2);

    Console.WriteLine("The length of side c is "   hypot);
  }
}

CodePudding user response:

You can use Console.ReadLine() - your value will be read into variable (if parsed) after pressing Enter:

using System;

public class Pythagorean {
  public static void Main() {
    double s1;
    double s2;
    double hypot;

    if (double.TryParse(Console.ReadLine(), out s1) && double.TryParse(Console.ReadLine(), out s2))
    {
        hypot = Math.Sqrt(s1*s1   s2*s2);

        Console.WriteLine("The length of side c is "   hypot);
    }
    else
    {
        Console.WriteLine("Invalid input - entered values cannot be parsed to double");
    }
  }    
}

The code can be simplified (inline variable declarations):

using System;

public class Pythagorean {
  public static void Main() {   
    if (double.TryParse(Console.ReadLine(), out var s1) 
        && double.TryParse(Console.ReadLine(), out var s2))
    {
        var hypot = Math.Sqrt(s1*s1   s2*s2);

        Console.WriteLine("The length of side c is "   hypot);
    }
    else
    {
        Console.WriteLine("Invalid input - entered values cannot be parsed to double");
    }
  }    
}

CodePudding user response:

using System;

public class Pythagorean
{
    public static void Main()
    {
        Console.Write("Enter s1: ");
        double s1 = double.Parse(Console.ReadLine());

        Console.Write("Enter s2: ");
        double s2 = double.Parse(Console.ReadLine());

        double hypot = Math.Sqrt(s1 * s1   s2 * s2);
        Console.WriteLine("The length of side c is "   hypot);
    }
}
  • Related