Home > OS >  calculator for binary number system
calculator for binary number system

Time:01-15

Can someone write me a calculator that takes two binary numbers and sums them up also multiplies them in C# (windows forms application), please? i tried this one but it's not working

private void button_Click(object sender, EventArgs e)
{          
    string[] array = { textBox1.Text, textBox2.Text, textBox3.Text };              
    label1.Text = GetNumberFormBinary(array);     
}

private string GetNumberFormBinary(string[] array)     
{       
    string result = "";      
    int _base = 2;       
    for (int i = 0; i < array.Length; i  )      
    {         
        int intValue = Convert.ToInt32(array[i], _base);         
        result  = intValue.ToString();      
    }
 
    return result;     
}

CodePudding user response:

As an alternative, you can query array and the result with a help of Linq:

using System.Linq;

...

private static string GetNumberFormBinary(string[] array) => array
  .Sum(item => Convert.ToInt32(item, 2))
  .ToString();

CodePudding user response:

You will first have to build the sum of values and only at the end turn the sum into a string, currently you are expanding your string with each individual value

So instead of

result  = intValue.ToString();

You have to do this

sum  = intValue;

Here the complete routine

private string GetNumberFormBinary(string[] array)     
{       
    int sum = 0;      
    int _base = 2;       
    for (int i = 0; i < array.Length; i  )      
    {         
        int intValue = Convert.ToInt32(array[i], _base);         
        sum  = intValue;      
    }
 
    return sum.ToString();     
}

As a side note, the problem with your code should have been obvious when you debugged your code and actually had a look what your code is doing and what values the variables have, so I would highly suggest learning how to debug your code:

https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger?view=vs-2022

  • Related