-2

I am trying to add two complex numbers from an GUI. I create 4 text-boxes - 2 are real number and 2 are imaginary numbers. I created an enter button. So, when I press enter it will display my results in a MessageBox.

I need help with displaying my results. I need it to display it in a way like this: 3 + 5i (where 3 is the sum of the real numbers and 5 is the sum of the imaginary number. I need the "i" to show up as well). I am getting a red line under this part: sum = ("{0} + {1}i",x ,y);

edited: So, now I want to do subtraction of the complex number. It shows no result for subtraction. Is it because I am not subtracting any vaule?

Here is my code:

    private double rPart1; // real number
    private double iPart1; // imaginary number
    private double rPart2; // real number
    private double iPart2; // imaginary number
    double x;
    double y;
    double call;
    double r;
    string sum;

    public string add()
    {
        rPart1 = Convert.ToDouble(textBoxReal1.Text);
        iPart1 = Convert.ToDouble(textBoxImaginary1.Text);
        rPart2 = Convert.ToDouble(textBoxReal2.Text);
        iPart2 = Convert.ToDouble(textBoxImaginary2.Text);

        x = rPart1 + rPart2;
        y = iPart1 + iPart2;

        sum = ("{0} + {1}i",x ,y);

        return sum;
    }

    public string sub()
    {

        x = rPart1 - rPart2;
        y = iPart1 - iPart2;

        subtract = (x + "-" + y + "i");

        return subtract;

    }

    private void buttonEnter_Click(object sender, EventArgs e)
    {
        sum = add();
        subtract = sub();
        MessageBox.Show("The addition is: " + sum
            + "\nThe subtraction is: " + subtract);
    }
Lebron Jamess
  • 109
  • 2
  • 12

3 Answers3

3

you need to write:

sum = string.Format("{0} + {1}i", x, y);

Btw. the .Net Framework 4.0 and onwards do have a complex number struct built in:

Complex Numbers in .Net 4.0

Adwaenyth
  • 2,020
  • 12
  • 24
0

You should use String.Format method:

string result = String.Format ("{0} + {1}i", x, y) ;
Maroun
  • 94,125
  • 30
  • 188
  • 241
Arnon Lauden
  • 136
  • 1
  • 4
0

you can do it in nice way.make a struct in your project like :

public struct MyNumber
{
public MyNumber(double rPart1,double iPart1,double rPart2,double iPart2){//Set fields value}
    private double rPart1;
    private double iPart1;
    private double rPart2;
    private double iPart2;
    public  double X { get { return rPart1 + rPart2 ; } }
    public  double Y { get { return iPart1 + iPart2; } }
    public  string Sum(string format)
    {
       return string.Format(format, X, Y);
     }
  }

and in your code

public string add()
{
   MyNumber number=new MyNumber(Convert.ToDouble(textBoxReal1.Text),Convert.ToDouble(textBoxImaginary1.Text),Convert.ToDouble(textBoxReal2.Text),Convert.ToDouble(textBoxImaginary2.Text));
   return number.Sum(custom format);
}
M.Azad
  • 3,673
  • 8
  • 47
  • 77