如何在 C# 中将字符串变量转换为双精度变量

How could I convert a string variable to a double in C#

我正在尝试将字符串变量转换为双精度变量。

到目前为止我已经尝试了 Convert.ToDouble()

string userAge;

Console.WriteLine("What is your age?");
Console.ReadLine();

Convert.ToDouble(userAge);

当我尝试对 userAge 进行操作时,它显示了这个错误:

Program.cs(23,27): error CS0019: Operator '/' cannot be applied to operands of type 'string' and 'double' [/home/ccuser/workspace/csharp-working-with-numbers-arithmetic-operators-csharp/e3-workspace.csproj]
Program.cs(29,28): error CS0029: Cannot implicitly convert type 'string' to 'double' [/home/ccuser/workspace/csharp-working-with-numbers-arithmetic-operators-csharp/e3-workspace.csproj]
Program.cs(17,24): error CS0165: Use of unassigned local variable 'userAge' [/home/ccuser/workspace/csharp-working-with-numbers-arithmetic-operators-csharp/e3-workspace.csproj]

The build failed. Fix the build errors and run again.

Any suggestions?

您没有将 Convert 调用的结果分配给变量,您只是将其丢弃。 Convert 不会改变现有变量的类型(因为除其他考虑外,您根本无法在强类型语言中这样做),而是生成一个新变量供您在数学中使用。

错误是,我假设没有看到相关代码,因为你试图在你的计算中使用 userAge,正如我刚刚解释的那样,它仍然是一个字符串。

此外,要后退一步,您实际上从未首先将 ReadLine 操作的结果分配给 userAge 变量。

这个:

Console.WriteLine("What is your age?");
string userAge = Console.ReadLine();
double age = Convert.ToDouble(userAge);

会更有意义。然后在之后的计算中使用 age

首先,您需要将这些方法调用的结果(获取用户输入,然后将字符串转换为双精度数)分配给一些变量,以便稍后在代码中使用它们:

Console.WriteLine("What is your age?");
string input = Console.ReadLine();
double age = Convert.ToDouble(input);

但现在我们看到了一个问题 - 如果用户输入非数字输入,我们将得到 FormatException

幸运的是,我们可以使用更好的方法将字符串解析为双精度值:double.TryParse。此方法接受一个 string(输入)和一个 out 参数,成功时它将设置为转换后的值(或失败时的默认值 0)。最好的是它 return 是一个 bool 指示它是否成功,因此我们可以将它用作循环的条件:

Console.Write("What is your age? ");
string userAge = Console.ReadLine();
double age;

while (!double.TryParse(userAge, out age))
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("Invalid input, please try again.");
    Console.ResetColor();
    Console.Write("What is your age? ");
    userAge = Console.ReadLine();
}

// Now 'age' is the converted value entered by the user

现在我们有了一个解决方案,它将循环直到用户输入有效数字。但这是相当多的代码。如果我们必须从他们那里得到另一个号码怎么办?可能最好将其提取到一个方法中,该方法接受 string(用作提示)并且 return 是强类型 double 结果:

public static double GetDoubleFromUser(string prompt)
{
    bool isValid = true;
    double result;

    do
    {
        if (!isValid)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Invalid input, please try again.");
            Console.ResetColor();
        }
        else isValid = false;

        Console.Write(prompt);
    } while (!double.TryParse(Console.ReadLine(), out result));

    return result;
}

现在我们的主要代码简单多了:

double userAge = GetDoubleFromUser("What is your age? ");
double userWeight = GetDoubleFromUser("What is your weight? ");

现在,如果我们想要更有趣一点,我们可以包含一个可选的 'validator' 参数,它是一个接受 double 和 return 的函数 bool,我们可以使用它来进一步验证结果并强制用户输入有效数字。

例如,如果我们希望他们从 110 中选择一个数字怎么办?我们不想为进一步的验证再次设置循环,所以让我们将 Func<double, bool> 传递给该方法,以便 it 可以为我们进行验证!

例如:

public static double GetDoubleFromUser(string prompt, Func<double, bool> validator = null)
{
    bool isValid = true;
    double result;

    do
    {
        if (!isValid)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Invalid input, please try again.");
            Console.ResetColor();
        }
        else isValid = false;

        Console.Write(prompt);
    } while (!double.TryParse(Console.ReadLine(), out result) &&
             (validator == null || !validator.Invoke(result)));

    return result;
}

现在我们可以传入我们想要对方法的输入进行的任何验证!这看起来类似于下面的代码行,并且在用户输入大于或等于 1 且小于或等于 10 的有效数字之前,该方法不会 return :

double number = GetDoubleFromUser("Choose a number from 1 to 10: ", 
    x => x >= 1 && x <= 10);