2. 隨機實數值轉換為等效二進制值

namespace Q2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var t = decimal.Parse(textBox1.Text);
            textBox2.Text = Convert.ToString((int)t, 2) + ".";
            var k = "";
            decimal v = t % 1;
            while (k.Length < 10 && v != 0)
            {
                v *= 2;
                k += (int)v;
                v %= 1;
            }
            textBox2.Text += k;

            if (textBox2.Text.EndsWith('0'))
                textBox3.Text = textBox2.Text.Substring(0, textBox2.Text.LastIndexOf('0'));
            else textBox3.Text = textBox2.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = $"{new Random().NextDouble() * 9999:0.0#####}";
        }
    }
}

Last updated