[英]How to calculate the surface of a square with user entries in C#?
我想編寫一個程序,用戶將被要求輸入用於計算正方形表面的數字。 但我不知道如何在我的方法中“使用”輸入的數字。
謝謝
這是我到目前為止所做的
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, not a valid floating point value; 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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.