3. 隨機八位元2的補數之整數相加與驗證系統
補數該複習了...
namespace Q3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
Close();
}
private void button2_Click(object sender, EventArgs e)
{
var rd = new Random();
string s = "";
for (int i = 0; i < 8; i++)
{
s += rd.Next(2);
}
textBox1.Text = s;
s = "";
for (int i = 0; i < 8; i++)
{
s += rd.Next(2);
}
textBox2.Text = s;
}
private void button1_Click(object sender, EventArgs e)
{
button3_Click(null, null);
int a = Convert.ToInt16(textBox1.Text.Substring(1), 2);
if (textBox1.Text.StartsWith("1")) a -= 128;
int b = Convert.ToInt16(textBox2.Text.Substring(1), 2);
if (textBox2.Text.StartsWith("1")) b -= 128;
int c = Convert.ToInt16(textBox3.Text.Substring(1), 2);
if (textBox3.Text.StartsWith("1")) c -= 128;
textBox8.Text = a + "";
textBox7.Text = b + ""; ;
textBox6.Text = c + "";
textBox5.Text = textBox4.Text == "" ? "" :
textBox4.Text == "overflow" ? "溢位" : "不足位";
}
private void button3_Click(object sender, EventArgs e)
{
int a = Convert.ToInt16(textBox1.Text.Substring(1), 2);
if (textBox1.Text.StartsWith("1")) a -= 128;
int b = Convert.ToInt16(textBox2.Text.Substring(1), 2);
if (textBox2.Text.StartsWith("1")) b -= 128;
textBox4.Text = "";
int r = a + b;
if (r < -128)
{
r = 128 + (r + 128);
textBox4.Text = "underflow";
}
else if (r > 127)
{
r = -128 + (r - 128);
textBox4.Text = "overflow";
}
bool neg = r < 0;
if (neg)
{
r += 128;
}
textBox3.Text = (neg ? 1 : 0) + Convert.ToString(r, 2).PadLeft(7, '0');
}
}
}
Last updated