【发布时间】:2016-12-11 08:44:48
【问题描述】:
我想在 Visual C# 中输入像 a/b 这样的小数值,但我不知道如何使用 Console.ReadLine() 命令为用户读取小数值。这个你能帮我吗。
谢谢。
【问题讨论】:
-
如果你在一行上读到的只是一个分数,你可以使用 Split('/') 将分子和分母作为单独的字符串。
标签: c# visual-studio stdin
我想在 Visual C# 中输入像 a/b 这样的小数值,但我不知道如何使用 Console.ReadLine() 命令为用户读取小数值。这个你能帮我吗。
谢谢。
【问题讨论】:
标签: c# visual-studio stdin
您是否尝试过 RegEx(和字符串修改)?
string Pattern = "\d+\/"; //Decimals, followed by a slash
string input = Console.ReadLine();
string topWS = Regex.Match(Pattern, input).Value //Will be something like 32/
string top = topWS.Value.Substring(0, topWS.Length - 1) //Will be 32
string bottom = input.Substring(topWS.Length)
Console.WriteLine(double.Parse(top) / double.Parse(bottom));
//Will return the fraction decimal value.
【讨论】:
string line = Console.ReadLine();
string[] values = line.Split('/');
诸如 13/64 之类的输入将为您提供 2 个字符串值。前 13 次,后 64 次。
【讨论】:
首先,你需要使用Console.Read()
那么你需要使用/ 来拆分参数分数,比如
string fraction = Console.Read();
string[] arrays = fraction.Split(new[] { '/' }, 2);
double numerator = int.Parse(arrays[0]);
double denominator = int.Parse(arrays[1]);
double x = numerator/denominator;
【讨论】:
new array 真的有必要吗?我很确定 .NET 将 {} 解析为一个数组。