gpt4 book ai didi

c# - 在 switch 语句中显示 Console.ReadLine()

转载 作者:太空宇宙 更新时间:2023-11-03 22:53:50 24 4
gpt4 key购买 nike

我正在构建控制台应用程序以提高我的 C# 技能。我有两个问题,我似乎无法在网上找到。

问题 1: 我想在输出中显示用户输入的任何内容(用户输入数值.. 当程序运行并显示答案时,我希望用户输入显示为嗯)..

问题 2: 目前您必须在第一次输入后按两次回车键才能继续。有没有办法只按一次回车键?

提前致谢!

这是现有代码(我将包括这两个类,以防您出于某种原因需要第二个类):

namespace StaticDemo {
class Program
{
static void Main(string[] args)
{
string selection = string.Empty;
while (selection != "q" && selection != "Q")
{
Console.Write("Enter C)elsius to Fahrentheit or F(ahrenheit to Celsius or Q(uit. \nSelect C, F, or Q then press the enter key twice to continue: ");
selection = Console.ReadLine();

double fahrenheit = 0, celsius = 0;
string line = Console.ReadLine();
switch (selection)
{

case "C":
case "c":
Console.Write("Please enter the Celsius temperature that you want converted to a Fahrenheit temperature: ");
fahrenheit = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
Console.WriteLine($"The temperature you provided in celsius: {line}, would be: {fahrenheit} in fahrentheit");
break;

case "F":
case "f":
Console.Write("Please enter the Farentheit temperature that you want converted to a Celsius temperature: ");
celsius = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
Console.WriteLine($"The temperature you provided in Fahrentheit: {line}, would be: {celsius} in celsius");
break;

case "Q":
case "q":
break;
default:
Console.WriteLine("Enter C F or a Q, Moron!");
break;

}
Console.WriteLine();
Console.WriteLine();
}
}
} }

如果您出于任何原因需要它,则下面是第二类代码:

namespace StaticDemo
{
class TemperatureConverter
{
public static double CelsiusToFahrenheit(string tempCelsius)
{
double celcius = double.Parse(tempCelsius);
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string tempFahrenheit)
{
double fahrenheit = double.Parse(tempFahrenheit);
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
}

最佳答案

这一行没用,是处理选择需要两次输入的原因

 string line = Console.ReadLine();

你已经阅读了两行的选择变量。

要获取用户提供的温度值,需要获取输入而不直接传递给转换类

  Console.Write("Please enter the Celsius temperature that you want converted to a Fahrenheit temperature: ");
string input = Console.ReadLine();
fahrenheit = TemperatureConverter.CelsiusToFahrenheit(input);
Console.WriteLine($"The temperature you provided in Celsius: {input}, would be: {celsius} in Fahrenheit");

当然,这同样适用于将华氏度转换为摄氏度的其他代码块。另请注意,我认为您已经颠倒了信息。

关于c# - 在 switch 语句中显示 Console.ReadLine(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46410496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com