简体   繁体   English

如何在此代码中要求 C# 中的用户输入,我需要一个函数来计算 pythagorean

[英]How do I ask for user input in C# in this code and I need a function to calculate the pythagorean

I'm building a pythagoras calculator in c# for school, but I can't figure out how I should change the lines: s1 = 3;我正在用 c# 为学校构建一个毕达哥拉斯计算器,但我不知道应该如何更改行:s1 = 3; and s2 = 4;和 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);
  }
}

You can use Console.ReadLine() - your value will be read into variable (if parsed) after pressing Enter :您可以使用Console.ReadLine() - 按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");
    }
  }    
}
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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM