C 语言教程 在线

1600c-examples-multiplication-table

乘法口决表递归实现方式:

#include <stdio.h>

void func(int i, int j)
{
    if(i>j)
        return;
    printf("%dx%d=%d\t", i, j, i*j);
    func(i+1, j);
}

void f(int n)
{
    if(n==1)
        printf("1x1=1\n");
    else
    {
        f(n-1);
        func(1, n);
        putchar('\n');
    }
}


int main()
{
    f(9);
    return 0;
}

1599c-examples-alphabet

三元运算符:

#include <stdio.h>

int main(){
  char c;
  printf("请输入一个字符:");
  scanf("%c",&c);
  ( (c>='a' && c<='z') || (c>='A' && c<='Z')) ? printf("%c是字母",c) : printf("%c不是字母",c);
  return 0;
}

1598c-examples-negative-positive-zero

还可以这样:

#include<stdio.h>

int main(){
    double  number;
    printf("请输入一个数字: ");
    scanf("%lf", &number);
    if(number < 0.0)
        printf("你输入的是负数>_<\n");
    else if(number > 0.0)
        printf("你输入的是正数-.-\n");
    else
        printf("你输入的是零0.0\n");
}

1597c-examples-leap-year

直接条件判断闰年:

#include <stdio.h>

int main()
{
    int year;
    printf("输入年份: ");
    scanf("%d",&year);
    // year = 400;

    // (四年一闰,百年不闰) || 四百年在闰年
    if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)    
    {
        printf("y\n");
    }
    else
    {
        printf("n\n");
    }

    return 0;
}

1596c-examples-leap-year

判断闰年还能这样写:

#include <stdio.h>

int main()
{
    int year;
    printf("输入年份: ");
    scanf("%d",&year);
    // year = 300;

    // 先处理百年,余下的在处理非百年
    if(year % 100 == 0)            // 先找出百年
    {
        if(year % 400 == 0)        // 找出 400年
        {
            printf("y\n");
        }
        else                    // 剩下就是是100年但不是400年
        {
            printf("n\n");
        }
    }
    else        // 剩下的是非百年的年份按照正常走
    {
        if(year % 4 == 0)
        {
            printf("y\n");
        }
        else
        {
            printf("n\n");
        }
    }

    return 0;
}

总体思路,先把特殊的百年年份拿出来,是 400 的倍数,是闰年,不是 400 的倍数,不是闰年。

然后,百年年份剩余的都为正常的非百年的年份直接按照 4 处理。