C prime plus(第六版)中文版 第十五章 课后习题

本文详细解答了C'++第六版中文版第十五章的课后习题,涵盖从第一题到第七题,包括开关状态的表示方法。

第一题

#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'){
       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值