C# 读取 double 类型的用户输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13813166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:52:20  来源:igfitidea点击:

read user input of double type

c#parsingloopsconsole

提问by trueCamelType

I have found this answered in other places using loops, but I wasn't sure if there is actually a function that I'm not finding that makes this easier, or if this is a possible (in my opinion) negative side to C#.

我已经在其他地方使用循环找到了这个答案,但我不确定是否真的有一个我没有找到的函数使这更容易,或者这是否可能(在我看来)对 C# 不利。

I'm trying to read in a double from user input like this:

我正在尝试从这样的用户输入中读取双精度:

Console.WriteLine("Please input your total salary: ") // i input 100
double totalSalary = Console.Read(); //reads in the 1, changes to 49.

I've found a couple other posts on this, and they all have different answers, and the questions asked aren't exactly the same either. If i just want the user input read in, what is the best way to do that?

我找到了一些关于此的其他帖子,它们都有不同的答案,所提出的问题也不完全相同。如果我只想读入用户输入,那么最好的方法是什么?

采纳答案by Simon Whitehead

You'll have to check the entire thing on it's way in.. as Console.Read()returns an integer.

你必须在它进入的路上检查整个事情......因为Console.Read()返回一个整数。

double totalSalary;
if (!double.TryParse(Console.ReadLine(), out totalSalary)) {
    // .. error with input
}
// .. totalSalary is okay here.

回答by John

string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
    Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);

回答by Versive

Simplest answer to your question:

最简单的回答你的问题:

double d = Double.Parse(Console.Readline());

回答by Dylan

Try this:

尝试这个:

double Salary = Convert.ToDouble(Console.ReadLine());