Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C หา 2's Complement ของเลขฐานสอง

ตัวอย่าง:

Input: Enter a binary number: 10010001

Output:

1's complement of 10010001 is 01101110

2's complement of 10010001 is 01101111

อัลกอริทึม

ขั้นตอน 1 - เริ่ม

ขั้นตอน 2 - อ่านเลขฐานสองตอนรันไทม์

ขั้นตอน 3 - คัดลอกเลขฐานสองไป strdp

ขั้นตอน 4 - len := strlen(str)

ขั้นตอน 5 - for i = 0 ถึง len-1: สลับ 0↔1 (หา 1's complement)

ขั้นตอน 6 - Mask := 1

ขั้นตอน 7 - for i = len-1 ถึง 0: บวก 1 เข้าไปใน 1's complement (หา 2's complement)

ขั้นตอน 8 - พิมพ์ 2's complement

ขั้นตอน 9 - หยุด

โปรแกรม

โปรแกรม C หา 2's complement ของเลขฐานสอง:

#include <string.h> #include<stdio.h> main(){    char str[32],strdp[32];    int mask,i;    printf("Enter a binary number:");    scanf("%s",str);    strcpy(strdp,str);    for(i=0;i<strlen(str);i++) /* computing 1's complement */{       if(str[i]=='1')          str[i]='0';       else          str[i]='1';    }    printf("1\'s complement of %s is %s\n",strdp,str);    mask=1;    for(i=strlen(str)-1;i>=0;i--){       if(mask==1){          if(str[i]=='1'){             str[i]='0';             mask=1;          }          else{             str[i]='1';             mask=0;          }       }    }    printf("2\'s complement of %s is %s",strdp,str); }

ผลลัพธ์

Enter a binary number:11001110 1's complement of 11001110 is 00110001 2's complement of 11001110 is 00110010