我如何在C#中将字符串变量转换为double类型

问题描述 投票:0回答:1

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

到目前为止,我已经尝试过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.

有什么建议吗?

c# syntax-error data-conversion
1个回答
0
投票

您没有将Convert调用的结果分配给变量,只是将其丢弃。转换不会更改现有变量的类型(因为您不能使用强类型语言执行此操作),而是会生成一个新变量供您在数学中使用。

错误是,我认为没有看到相关的代码,因为您尝试在计算中使用userAge,正如我刚才所解释的,它仍然是一个字符串。

另外,要倒退一步,您实际上从未将剩余的ReadLine操作首先分配给userAge变量。

© www.soinside.com 2019 - 2024. All rights reserved.