簡體   English   中英

使用C#中的Double.TryParse方法轉換字符串

[英]Converting a string using the Double.TryParse method in C#

現在,我將所有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 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 );

輸出:

defaultValue = 0

成功=錯誤

成功案例:

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

輸出:

defaultValue = 123

成功=真

我認為你只是試圖強制使用輸入正確的值,你可以像這樣使用wile循環

 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;
            }

        }

然后適用於你的所有問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM