简体   繁体   English

二进制数系统计算器

[英]calculator for binary number system

Can someone write me a calculator that takes two binary numbers and sums them up also multiplies them in C# (windows forms application), please?有人可以给我写一个计算器,它可以接受两个二进制数并将它们相加并在 C#(Windows forms 应用程序)中将它们相乘吗? 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;     
}

As an alternative, you can query array and the result with a help of Linq :作为替代方案,您可以在Linq的帮助下查询array和结果:

using System.Linq;

...

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

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 https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger?view=vs-2022

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM