我想编写一个程序,在该程序中,系统将要求用户提供用于计算正方形表面的数字。但是我不知道如何在我的方法中“使用”输入的数字。
谢谢
这是我到目前为止所做的
static void Main(string[] args)
{
calculate();
}
public static void Height()
{
Console.WriteLine("Enter height of the square");
string enter1 = Console.ReadLine();
double height = Convert.ToDouble(enter1);
// height of the square
}
public static void Length()
{
Console.WriteLine("Enter length of the square");
string enter2 = Console.ReadLine();
double length = Convert.ToDouble(enter2);
//length of the square
}
static double calculate(double a, double b)
{
double summary = a * b;
Console.WriteLine(summary);
return summary;
}
}
返回并使用您首先输入的内容,以确保您获得成功:
static void Main(string[] args)
{
calculate(Height(), Length());
}
public double void Height()
{
Console.WriteLine("Enter height of the square");
string enter1 = Console.ReadLine();
return Convert.ToDouble(enter1);
// height of the square
}
public static double Length()
{
Console.WriteLine("Enter length of the square");
string enter2 = Console.ReadLine();
return Convert.ToDouble(enter2);
//length of the square
}
static double calculate(double a, double b)
{
double summary = a * b;
Console.WriteLine(summary);
return summary;
}
}
如果我没有错别字,那么这应该对您有用,但是您仍有很多要学习的地方。您应该将I / O操作与计算的业务逻辑分开,并且为了可重用性和可移植性,两者之间应仅进行精简通信。我没有在上面的代码中这样做,它留给您作为家庭作业。
首先,我建议提取一种方法(读取double
值:]
public static double ReadDouble(string title) {
// while (true) - keep on asking until valid value provided
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
// TryParse: user can enter any input here, say, "bla-bla-bla"
// we don't want any exceptions here
if (double.TryParse(Console.ReadLine(), out double result))
return result;
Console.WriteLine("Sorry, invalid syntax; please, try again");
}
}
然后我们可以实现主例程:
static void Main(string[] args)
{
double height = ReadDouble("Enter height of the rectangle");
double width = ReadDouble("Enter width of the rectangle");
double square = height * width;
Console.WriteLine($"The square of the {width} x {height} rectangle is {square}");
// Pause (wait for a keypress) for user to read the answer
Console.ReadKey();
}