【问题标题】:Converting a string using the Double.TryParse method in C#在 C# 中使用 Double.TryParse 方法转换字符串
【发布时间】:2019-04-04 16:44:39
【问题描述】:

现在,我将所有 3 个字符串都转换为一个 int,但是我在使用 Double.TryParse 方法转换每个字符串时遇到了麻烦。我想使用该方法而不是 int。

我尝试使用这种类型的代码 if (Double.TryParse(value, out number)),但我不确定这是否正确。

//Ask the user for height
Console.Write("Please enter the first part of your height in feet:");
string _height = Console.ReadLine();
int _heightVal = Int32.Parse(_height);

//Ask the user for inches
Console.Write("Please enter the second part of your height in inches:");
string _inches = Console.ReadLine();
int _inchesVal = Int32.Parse(_inches);

//Ask the user for pounds
Console.Write("Please enter your weight in pounds:");
string _pounds = Console.ReadLine();
int _poundsVal = Int32.Parse(_pounds);

【问题讨论】:

  • 我看不到你在哪里使用Double.TryParse
  • tryparse 应该包含在 if 中,您可以在其中以某种方式处理故障。 docs.microsoft.com/en-us/dotnet/api/…
  • Double 似乎是英尺和英寸的错误选择。也许是重量,但如果是小数,也许使用小数。

标签: c# string double


【解决方案1】:
double heightVal = 0;
double.TryParse(_height, out heightVal); 

如果解析成功,heightVal 将具有来自 _height 的 Parse 的值,否则它将具有它之前的值(此处为 0)

TryParse() 返回一个布尔值,指示解析是否成功,您可以像这样使用它:

bool success = double.TryParse(_height, out heightVal); 

if(double.TryParse(_height, out heightVal))
{
     //Parse was successful and heightVal contains the new value
     // and you can use it in here
}

失败示例:

double defaultValue = 0;
string str = "abc"
bool success = double.TryParse(str, defaultValue );

输出:

默认值 = 0

成功 = 假

成功范例:

double defaultValue = 0;
string str = "123"
bool success = double.TryParse(str, defaultValue );

输出:

默认值 = 123

成功 = 真

【讨论】:

  • 可能想要添加一个利用返回的布尔值的示例。
  • @JonathonChase 我正在做 ;)
【解决方案2】:

我认为您只是想强制使用输入正确的值 你可以使用诡计循环 像这样

 double userHeight = 0.0;
        while (true)
        { 
            //Ask the user for height
            Console.Write("Please enter the first part of your height in feet:");
            string _height = Console.ReadLine();
            if (Double.TryParse(_height, out double height))
            {
                userHeight = height;
                break;
            }

        }

然后应用到你所有的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多