[英]I'm a beginner and write console programs I'm trying to build a calculator and need help (C#)
I want to know how to use a user input similar to Convert.ToInt64(Console.Readline())
but if they type eg: 198.98我想知道如何使用类似于
Convert.ToInt64(Console.Readline())
的用户输入,但如果他们输入例如:198.98
Into the floating point type you prefer var doesn't work I don't know what else to do进入你喜欢的浮点类型 var 不起作用我不知道还能做什么
you can use this:你可以使用这个:
float.TryParse(Console.Readline());
You should use this method instead of using the Convert class.您应该使用此方法而不是使用 Convert class。 If you want to make sure your program doesn't throw an exception, try
float.TryParse()
instead.如果您想确保您的程序不会引发异常,请尝试
float.TryParse()
代替。
var f = float.Parse(Console.ReadLine());
Console.WriteLine(f);
Console.ReadLine();
What does the var part look like? var部分是什么样的?
You should check the input parameter and then try to cast it.您应该检查输入参数,然后尝试强制转换它。 use try parse to cast
使用 try parse 进行强制转换
if(double.TryParse(request.Code, out var doubleNumber))
{
throw new ArgumentException();
}
read this doc: https://docs.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-6.0阅读此文档: https://docs.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-6.0
Make sure that the user only can input number.确保用户只能输入数字。
var a = float.Parse(Console.ReadLine());
Console.WriteLine(a);
Or或者
double b = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(b);
You can also read this article你也可以阅读这篇文章
https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/numbers-in-csharp-local https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/numbers-in-csharp-local
We have various options for performing this conversion.我们有多种选择来执行这种转换。 The difference between float and double is that float has four places after the decimal point and double has twelve places after the decimal point.
float 和 double 的区别在于 float 小数点后有 4 位,double 小数点后有 12 位。 So of you want double you can use it as,
所以你想要双倍的你可以用它,
var num = Convert.ToDouble(Console.ReadLine()) var num = Convert.ToDouble(Console.ReadLine())
In case if you want to convert it into float we have two options there, parse and tryparse.如果你想把它转换成浮点数,我们有两个选项,parse 和 tryparse。 Parse returns the converted number and TryParse returns the Boolean value of conversion.
Parse 返回转换后的数字,TryParse 返回转换后的 Boolean 值。 You can use it accordingly like,
您可以相应地使用它,例如,
var num = float.Parse(Console.ReadLine()) var num = float.Parse(Console.ReadLine())
try this one: for your situation you have to use below code:试试这个:对于您的情况,您必须使用以下代码:
Convert.ToDouble(Console.Readline());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.