read user input of double type

2019-02-22 05:36发布

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#.

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?

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-22 05:44

Try this:

double Salary = Convert.ToDouble(Console.ReadLine());
查看更多
Anthone
3楼-- · 2019-02-22 05:52

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

double totalSalary;
if (!double.TryParse(Console.ReadLine(), out totalSalary)) {
    // .. error with input
}
// .. totalSalary is okay here.
查看更多
成全新的幸福
4楼-- · 2019-02-22 05:57

Simplest answer to your question:

double = Double.Parse(Console.Readline());
查看更多
成全新的幸福
5楼-- · 2019-02-22 05:59
string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
    Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);
查看更多
登录 后发表回答