我最近在课程中从c++转到了c#,但是我搜索了很多地方都没有找到太多相关信息。我遇到了以下问题:我应该让用户添加一个复数。例如:
-3.2 - 4.1i 我想要将其拆分并存储为(-3.2) - (4.1i)
我知道可以在负号处进行拆分,但是还存在一些问题,比如
4 + 3.2i 或者只有一个数字3.2i。
任何帮助或见解都将不胜感激。
通过使用正则表达式匹配所有有效的输入,然后进行组装即可。正则表达式的工作原理是:
[0-9]+
匹配 0-n 个数字[.]?
匹配 0 或 1 个点[0-9]+
匹配 0-n 个数字i?
匹配 0 或 1 个 "i"|
或者[+-*/]?
匹配 0 或 1 个运算符 +、-、* 或 /.
public static void ParseComplex(string input)
{
char[] operators = new[] { '+', '-', '*', '/' };
Regex regex = new Regex("[0-9]+[.]?[0-9]+i?|[+-/*]?");
foreach (Match match in regex.Matches(input))
{
if (string.IsNullOrEmpty(match.Value))
continue;
if (operators.Contains(match.Value[0]))
{
Console.WriteLine("operator {0}", match.Value[0]);
continue;
}
if (match.Value.EndsWith("i"))
{
Console.WriteLine("imaginary part {0}", match.Value);
continue;
}
else
{
Console.WriteLine("real part {0}", match.Value);
}
}
}
这仍然存在许多缺陷和可能出现问题的方式,但它有点工作。
struct Complex
{
float re, im;
public static Complex Parse(string text)
{
text=text.Replace(" ", string.Empty); //trim spaces
float re=0, im=0;
int i_index=text.IndexOf('i');
if(i_index>=0) //if no 'i' is present process as real only
{
text=text.Substring(0, i_index); //ignore all after i
int i=0;
//find start of digits
while(i<text.Length&&(text[i]=='+'||text[i]=='-'))
{
i++;
}
//find end of digits
while(i<text.Length&&(char.IsNumber(text, i)|| text.Substring(i).StartsWith(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)))
{
i++;
}
// parse real (first) portion
float.TryParse(text.Substring(0, i), out re);
// had 'i' but no numbers
if(text.Length==0)
{
im=1;
}
else
{
//parse remaining value as imaginary
text=text.Substring(i+1);
float.TryParse(text, out im);
}
}
else
{
float.TryParse(text, out re);
}
// Build complex number
return new Complex() { re=re, im=im };
}
public override string ToString()
{
return string.Format("({0},{1})", re, im);
}
}
class Program
{
static void Main(string[] args)
{
var test=new[] { "1", "i", "5+2i", "-5+2i", "+5-2i", "0.23+0.72i" };
for(int i=0; i<test.Length; i++)
{
Debug.Print( Complex.Parse(test[i]).ToString() );
}
}
}
结果:
(1,0)
(0,1)
(5,2)
(-5,2)
(5,2)
(0.23,0.72)
[0-9]?[.][0-9]?i?
的东西。 - defaultSystem.Numerics.Complex
没有任何类型的Parse
方法 - 因此适用于存储,但无法用于解析。 - Alexei Levenkov1e-3+4.2e-2i
或其他浮点数呢?还有5i-1
。看起来你需要一个相当强大的表达式解析器。 - John Alexiou