winforms 如何在c#中用分数解决二进制到十进制的问题?我尝试用winform把二进制数转换成十进制,我用了input函数

c8ib6hqw  于 2023-02-24  发布在  C#
关注(0)|答案(1)|浏览(135)
if (binarybtn.Checked == true)
{
    int decVal = 0, baseVal = 1, rem;
    binarytxtbox.Text = textBox1.Text;

    int input = Convert.ToInt32(textBox1.Text);

    while (input > 0)
    {
        rem     = input % 10;
        decVal  = decVal + rem * baseVal;
        input   = input / 10;
        baseVal = baseVal * 2;
    }

    decimaltxtbox.Text = Convert.ToString(decVal);

    ...

我尝试使用input函数,但它 * 不接受 * 字符串"."

9lowa7mx

9lowa7mx1#

如果我没理解错的话,你有一个带小数部分的二进制数,就像

10.1 (binary)

你想把它转换成一个对应的十进制数,在上面的例子中,它是

2.5 (decimal)

如果这是你的任务,你可以用

private static decimal BinaryToDecimal(string value, char decimalSeparator = '.') {
  value = value.Trim();

  int sign = value.StartsWith('-') ? -1 : 1;

  value = value.Trim('-');

  int index = value.IndexOf(decimalSeparator);

  string integerPart = index >= 0 ? value.Substring(0, index) : value;

  decimal result = string.IsNullOrEmpty(integerPart)
    ? 0
    : Convert.ToInt64(integerPart, 2);

  string fractionalPart = index >= 0 ? value.Substring(index + 1) : "";

  for (int i = 0; i < fractionalPart.Length; ++i)
    result += (decimal)(fractionalPart[i] - '0') / (1L << (i + 1));

  return sign * result;
}

用法:

decimaltxtbox.Text = $"{BinaryToDecimal(binarytxtbox.Text)}";

演示:

using System.Linq;

...

string[] tests = {
  "0",
  "-0",
  "100",
  "-100",
  "10.",
  "-10.",
  "1.1",
  "101.101",
  "-101.101",
  ".1011",
  "-.11011",
  "100.00",
  ".", // <- It seems, you treat it as a valid input
};

string report = string.Join(Environment.NewLine, tests
  .Select(test => $"{test,10} => {BinaryToDecimal(test)}"));

Console.Write(report);

输出:

0 => 0
        -0 => 0
       100 => 4
      -100 => -4
       10. => 2
      -10. => -2
       1.1 => 1.5
   101.101 => 5.625
  -101.101 => -5.625
     .1011 => 0.6875
   -.11011 => -0.84375
    100.00 => 4
         . => 0

如果您正在寻找 reverse(即从十进制到二进制)转换,请查看
如何将十进制分数转换为十六进制分数?

相关问题