首先,用二进制数字声明和初始化两个变量。
val1 = 11010; val2 = 10100; Console.WriteLine("Binary one: " + val1); Console.WriteLine("Binary two: " + val2);
要求和,请循环直到两个值都为0。
while (val1 != 0 || val2 != 0) { sum[i++] = (val1 % 10 + val2 % 10 + rem) % 2; rem = (val1 % 10 + val2 % 10 + rem) / 2; val1 = val1 / 10; val2 = val2 / 10; }
现在,让我们看一下完整的代码来查找两个二进制数的和。
using System; class Demo { public static void Main(string[] args) { long val1, val2; long i = 0, rem = 0; long[] sum = new long[30]; val1 = 11010; val2 = 10100; Console.WriteLine("Binary one: " + val1); Console.WriteLine("Binary two: " + val2); while (val1 != 0 || val2 != 0) { sum[i++] = (val1 % 10 + val2 % 10 + rem) % 2; rem = (val1 % 10 + val2 % 10 + rem) / 2; val1 = val1 / 10; val2 = val2 / 10; } if (rem != 0) sum[i++] = rem; i = i - 1; Console.Write("Sum = "); while (i >= 0) Console.Write(sum[i--]); } }
输出结果
Binary one: 11010 Binary two: 10100 Sum = 101110