第一题
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char * sgets(char st[], int n);
int cal(char *pb, int n);
int main()
{
printf("15.9.1:\n");
int num;
char pbin[9];
sgets(pbin,9);
num=cal(pbin,9);
printf("The number is : %d.",num);
}
char *sgets(char *st, int n){
char * ret_val;
int i=0;
ret_val=fgets(st,n,stdin);
if(ret_val){
while(st[i]!='\n' && st[i]!='\0')
i++;
if(st[i] == '\n')
st[i]='\0';
else
while(getchar()!='\n')
continue;
}
return ret_val;
}
int cal(char *pb, int n){
int value=0;
int m;
for(int i=n-2;i>=0;i--,*pb++){
m=*pb-48;
value+=m*(pow(2,i));
}
return value;
}
第二题
#include <stdio.h>
#include <stdlib.h>
char *get(char *st,int n);
void f(char *st);
void and(char *st1, char*st2);
void or(char *st1,char*st2);
void not(char *st1,char*st2);
int main()
{
printf("15.9.2!\n");
char s1[9];
char s2[9];
printf("Enter the first sting: ");
get(s1,9);
printf("\nEnter the second string: ");
get(s2,9);
printf("one(~):\n");
f(s1);
printf("\n");
f(s2);
printf("\ntwo(&):\n");
and(s1,s2);
printf("\nthree(|):\n");
or(s1,s2);
printf("\nfour(^):\n");
not(s1,s2);
return 0;
}
char *get(char *st,int n){
char *ret_val;
int i=0;
ret_val=fgets(st,n,stdin);
if(ret_val){
while(st[i] != '\n' && st[i] != '\0')
i++;
if(st[i] == '\n')
st[i]='\0';
else
while(getchar() != '\n')
continue;
}
return ret_val;
}
void f(char *st){
char *pb=st;
while(*pb != '\0'){
if(*pb=='0')
printf("1");
else
printf("0");
*pb++;
}
}
void and(char *st1, char*st2){
char *pb1=st1;
char* pb2=st2;
while(*pb1 != '\0'){
if(*pb1=='1' && *pb2=='1')
printf("1");
else
printf("0");
*pb1++;
*pb2++;
}
}
void or(char *st1,char*st2){
char *pb1=st1;
char *pb2=st2;
while(*pb1 !='\0'){
if(*pb1=='1' || *pb2=='1')
printf("1");
else
printf("0");
*pb1++;
*pb2++;
}
}
void not(char *st1,char*st2){
char *pb1=st1;
char *pb2=st2;
while(*pb1 !='\0'){