>  기사  >  백엔드 개발  >  숫자가 주어지면 2의 보수 C 프로그램을 찾으세요.

숫자가 주어지면 2의 보수 C 프로그램을 찾으세요.

PHPz
PHPz앞으로
2023-09-18 09:17:05826검색

숫자가 주어지면 2의 보수 C 프로그램을 찾으세요.

给定二进制数的补码可以通过两种方法计算,如下 -

  • 方法 1 − 将给定的二进制数转换为补码,然后加 1。

  • 方法 2 − 从 Least 开始设置的第一个位后面的尾随零有效位 (LSB),包括保持不变的一位,其余全部应补码。

对于给定的二进制数查找二进制补码的逻辑如下 -

for(i = SIZE - 1; i >= 0; i--){
   if(one[i] == '1' && carry == 1){
      two[i] = '0';
   }
   else if(one[i] == '0' && carry == 1){
      two[i] = '1';
      carry = 0;
   } else {
      two[i] = one[i];
   }
}
two[SIZE] = '\0';
printf("Two&#39;s complement of binary number %s is %s</p><p>",num, two);

从给定的二进制数中找到补码的逻辑是 −

for(i = 0; i < SIZE; i++){
   if(num[i] == &#39;0&#39;){
      one[i] = &#39;1&#39;;
   }
   else if(num[i] == &#39;1&#39;){
      one[i] = &#39;0&#39;;
   }
}
one[SIZE] = &#39;\0&#39;;
printf("Ones&#39; complement of binary number %s is %s</p><p>",num, one);

示例

以下是查找给定数字的补码的 C 程序 -

 现场演示

#include<stdio.h>
#include<stdlib.h>
#define SIZE 8
int main(){
   int i, carry = 1;
   char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
   printf("Enter the binary number</p><p>");
   gets(num);
   for(i = 0; i < SIZE; i++){
      if(num[i] == &#39;0&#39;){
         one[i] = &#39;1&#39;;
      }
      else if(num[i] == &#39;1&#39;){
         one[i] = &#39;0&#39;;
      }
   }
   one[SIZE] = &#39;\0&#39;;
   printf("Ones&#39; complement of binary number %s is %s</p><p>",num, one);
   for(i = SIZE - 1; i >= 0; i--){
      if(one[i] == &#39;1&#39; && carry == 1){
         two[i] = &#39;0&#39;;
      }
      else if(one[i] == &#39;0&#39; && carry == 1){
         two[i] = &#39;1&#39;;
         carry = 0;
      }
      else{
         two[i] = one[i];
      }
   }
   two[SIZE] = &#39;\0&#39;;
   printf("Two&#39;s complement of binary number %s is %s</p><p>",num, two);
   return 0;
}

输出

当执行上述程序时,会产生以下结果 -

Enter the binary number
1000010
Ones&#39; complement of binary number 1000010 is 0111101
Two&#39;s complement of binary number 1000010 is 0111110

위 내용은 숫자가 주어지면 2의 보수 C 프로그램을 찾으세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제