怎么将a+bi形式的字符串转变成复数呢这是我的转换的代码,这样错不知道怎么改了,待大神指教
你写是个啥写这么多都没用,你用int i = s.IndexOf("+", 0);就能找到+所在的索引,楼上的回答很简洁实用。string操作并不只是substring,你直接用split('+')就能把你的字符串分成两个部分就是实部和虚部i。你再split('i')[0]或者replace('i',"")用空格填充然后trim格式化去掉空格。
string s = "123+5i";
double real, image;
real = double.Parse(s.Split('+')[0]);
image = double.Parse(s.Split('+')[1].Split('i')[0]);
Complex cop = new Complex(real, image);
你用substring也能弄出来
string s = "123+5i";
double real, image;
real = double.Parse(s.Substring(0, s.IndexOf('+')));
image = double.Parse(s.Substring(s.IndexOf('+'),s.Length - 1 - s.IndexOf('+')));
看着麻烦还容易出错
假设基于
http://ask.csdn.net/questions/247718
这里我的代码
string s = "1+2i";
int x = int.Parse(s.Split('+')[0].Trim());
int y = int.Parse(s.Split('+')[1].Replace("i", "").Trim());
Complex c = new Complex(x, y);
如果问题解决(包括上个问题),请帮我采纳下,方法是点我回答右边的采纳按钮。谢谢
忘了说了你要引用using System.Numerics;找一下这个.net组件他的复数形式就是(123,5)形式,应该可以进行复数间的运算操作,我没试过
我再帮你考虑下实部虚部有负数的情况
string s = "-123-5i";
double real, image;
if (s.Contains('+'))
{
real = double.Parse(s.Split('+')[0]);
image = double.Parse(s.Split('+')[1].Split('i')[0]);
}
else
{
real = double.Parse(s.Substring(0, s.LastIndexOf('-')));
image = double.Parse(s.Substring(s.LastIndexOf('-'), s.Length - 1 - s.LastIndexOf('-')));
}
Complex cop = new Complex(real, image);