现在,我将所有 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 heightVal = 0;
double.TryParse(_height, out heightVal);
如果解析成功,heightVal 将具有来自 _height
的 Parse 的值,否则它将具有它之前的值(此处为 0)
TryParse()
返回一个 bool 值,指示解析是否成功,您可以像这样使用它:
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 );
Output:
defaultValue = 0
success = false
成功范例:
double defaultValue = 0;
string str = "123"
bool success = double.TryParse(str, defaultValue );
Output:
defaultValue = 123
success = true
关于c# - 在 C# 中使用 Double.TryParse 方法转换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521149/