算法竞赛入门经典第三章

本文详细解析了C语言基础习题,包括计算器功能实现、字符数组旋转和不同进制转换,通过实例代码深入理解C语言的基础应用。

习题3-4 计算器(calculator)

#include <math.h>
int main()
{
    int n1,n2;
    char f;
    scanf("<strong><span style="color:#ff0000;">%d %c%d</span></strong>",&n1,&f,&n2);
    switch(f)
    {
        case '+': printf("%d", n1 + n2);break;
        case '-': printf("%d", n1 - n2);break;
        case '*': printf("%d", n1 * n2);
    }
    return 0;
}

习题3-5 旋转(rotate)

#include <stdio.h>
#include <stdlib.h>
#define N 1000
char array[N][N];
int main()
{
    int n, i, j;
    scanf("%d", &n);
    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)
            scanf("<span style="color:#ff0000;"><strong> %c</strong></span>",&array[i][j]);
    for(j = n - 1; j > -1; j--)
    {
        for(i = 0; i < n; i++)
            printf("%c ",array[i][j]);
        printf("\n");
    }
    return 0;
}


summary: 

scanf中%d%c有些小区别。以下是reference:"

Because most conversion specifiers first consume all consecutive whitespace, code such as

std::scanf("%d", &a);
std::scanf("%d", &b);

will read two integers that are entered on different lines (second %d will consume the newline left over by the first) or on the same line, separated by spaces or tabs (second %d will consume the spaces or tabs).

The conversion specifiers that do not consume leading whitespace, such as %c, can be made to do so by using a whitespace character in the format string:
std::scanf("%d", &a);
std::scanf(" %c", &c); // ignore the endline after %d, then read a char



%d可以忽略与前一个输入之间的所有空格和TAB,但%c不行,所以在“%c”时把格式写程“ %c”,这样它也就可以忽略与前一个输入之间的所有空格和TAB了


习题3-6 进制转换1(base1)

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int base, n, i, count = 0, arr[100];
    scanf("%d%d",&base, &n);
    while(n != 0)
    {
        arr[count++] = n % base;
        n = n / base;
    }
    for(i = count - 1; i > -1; i--)
        printf("%d", arr[i]);
    printf("\n");
    return 0;
}


习题3-7 进制转换2(base2)

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int base, n, b = 1, sum = 0;
    scanf("%d%d",&base, &n);
    while(n != 0)
    {
        sum = sum + b * (n % 10);
        b = b * base;
        n = n / 10;
    }
    printf("%d\n",sum);
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值