C语言案例
本文最后更新于531 天前,其中的信息可能已经过时,如有错误请发送至评论区或邮箱alore@can6.top

此文章为学习C语言时的案例笔记,用于记录各种案例。由于是从其他地方迁移至此,格式稍有错误。

  • 分支结构

     

    if(){
    ...
    }else{
    ...
    }
    
    switch(){
    case():...;break;
    default:...;
    }
    
    continue/break
    
    //for循环不能用continue
    
  • 简单计算器

     

      #include 
      int main(void)
      { int value1, value2; char op;
      printf ("Type in an expression: "); 
      scanf ("%d%c%d", &value1, &op, &value2); 
      switch (op){
      case '+': printf ("=%d\n", value1 + value2); break;
      case '-': printf ("=%d\n", value1 - value2); break;
      case '*': printf ("=%d\n", value1 * value2); break;
      case '/':
      if (value2 != 0) printf ("=%d\n", value1 / value2);
      else printf ("Divisor can not be 0!\n");
      break;
      case '%':
      if (value2 != 0) printf ("=%d\n", value1 % value2);
      else printf ("Divisor can not be 0!\n");
      break;
      default: printf ("Unknown operator\n"); break;
      }
      return 0;
      }
    
  • 字符类型


    Char → %d

    挨个读取字符 → getchar ()

      ch = getchar ()
      
      putchar ()
    
  • 第三章
  • 格雷戈里求圆周率

     

      #include 
      int main (void)
      {
      int denominator, flag;
      double item, pi;
      flag = 1; denominator = 1; item = 1.0; pi = 0;
      while (fabs (item) >= eps) {
      pi = pi + item;
      flag = -flag;
      denominator = denominator + 2;
      item = flag * 1.0 / denominator;
      }
      pi = pi + item;
      pi = pi * 4;
      printf ("pi = %.4f\n"
      , pi);
      return 0;
      }
    
  • 统计学生成绩

     

      # include 
      int main (void)
      { int count, num; double score, total;
      num = 0; total = 0; count=0;
      printf ("Enter scores: \n");
      scanf ("%lf", &score); /* 输入第1个数*/
      while (score >= 0) { /* 输入负数,循环结束 */
      total = total + score;
      num++;
      if (score < 60) {
      count++;
      }
      scanf ("%lf", &score);
      }
      if (num != 0) {
      printf("Average is %.2f\n", total/num);
      printf("Number of failures is %d\n", count);
      } else {
      printf("Average is 0\n");
      }
      return 0;
      }
    
  • 统计位数


    do while循环

      do{
      ...
      }while(...);
    

     

      #include
      int main (void)
      { int count, number;
      printf ("Enter a number: ");
      scanf ("%d", &number) ;
      if (number < 0){
      number = -number;
      }
      count = 0;
      do {
      number = number / 10;
      count ++;
      } while (number != 0);
      printf ("It contains %d digits.\n", count);
      return 0;
      }
    
  • 判断素数

     

      int main (void)
      { int count, number;
      printf ("Enter a number: ");
      scanf ("%d", &number) ;
      if (number < 0){
      number = -number;
      }
      count = 0;
      do {
      number = number / 10;
      count ++;
      } while (number != 0);
      printf ("It contains %d digits.\n", count);
      return 0;
      }
    
  • 函数
  • 计算圆柱体积

     

      # include 
      double cylinder (double r, double h); /* 函数声明*/
      int main( void )
      {
      double height, radius, volume;
      printf ("Enter radius and height: ");
      scanf ("%lf%lf", &radius, &height);
      /* 调用函数,返回值赋给volume */
      volume = cylinder (radius, height );
      printf ("Volume = %.3f\n", volume);
      return 0;
      }
      
      double cylinder (double r, double h)
      {
      double result;
      result = 3.1415926535*r*r;
      }
    


  •   double a1, a2, a3, a4, a5, a6, a7,s;
      double area(double x, double y, double z);
      printf("Please input 7 side lengths in the order a1 to a7:\n");
      scanf("%lf%lf%lf%lf%lf%lf%lf", &a1, &a2, &a3, &a4, &a5, &a6, &a7); 
      s = area(a1, a5, a6) + area(a4, a6, a7) + area(a2, a3, a7); /* 调用3次area */
      printf("The area of the Pentagon is %.2f\n", s) ;
      /* 使用海伦-秦九韶公式计算三角形面积的函数 */
      double area(double x, double y, double z) /* 函数首部 */
      {
      double p = (x + y + z) / 2;
      return sqrt(p * ( p - x ) * ( p - y ) * ( p - z )) ; 
      }
      
    
  • 数组
  • 定义数组时,对数组元素赋初值

     

      //类型名 数组名[数组长度] = {初值表};
      int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      
      ==>  a[0]=1, a[1]=2, ...… a[9]=10
    
  • 静态数组、动态数组的初始化

     

      //静态存储的数组如果没有初始化,所有元素自动赋0
      static int b[5];
      //动态存储的数组如果没有初始化,所有元素为随机值
      auto int c[5]; 等价于 int c[5];
      
      example:
      static int b[5] = {1, 2, 3};
      b[0] = 1, b[1] = 2, b[2] = 3, b[3] = 0, b[4] = 0
      auto int fib[20] = {0, 1};
      fib[0] = 0, fib[1] = 1, 其余元素不确定
    
  • 定义数组

     

      #include
      #define MAXN 10
      int main (){
      int a[MAXN];
      ...
      return 0;
      }
    
  • 求最小值

     

      min = a[0];
      for (i=1,i<n,i++){
      if (a[i] < min){
      min = a[i];
      }
      }
    
  • 二分法查找

     

      low = 0; 
      high = n - 1; /* 开始时查找区间为整个数组 */
      while ( low <= high ) { /* 循环条件 */
      mid = (low + high) / 2; /* 中间位置 */
      if ( x == a[mid] ){
      break; /* 查找成功,中止循环 */
      }else if ( x < a[mid] ){
      high = mid - 1; /* 新查找区间为前半段,high前移 */
      }else{ 
      low = mid + 1; /* 新查找区间为后半段,low后移 */
      }
      } 
      if ( low <= high ){ printf("Index is %d \n", mid);
      }else{ printf( "Not Found\n");
      }
    
  • 二维矩阵找最大值

     

      # define MAXM 6
      # define MAXN 6
      int a[MAXM][MAXN];
      printf ("Enter m, n: "); scanf ("%d%d", &m, &n);
      printf("Enter %d integers: \n", m*n);
      for ( i = 0; i < m; i++ ){
      for ( j = 0; j < n; j++ ){
      scanf ("%d", &a[i][j]);}
      }
      row = col = 0;
      for ( i = 0; i < m; i++ ){
      for ( j = 0; j < n; j++ ){
      if ( a[i][j] > a[row][col] ){
      row = i;
      col = j;
      }}
      }
      printf ( "max = a[%d][%d] = %d\n", row, col, a[row][col] );
    
  • 矩阵
  • 二维矩阵初始化

     

      分行赋初值
      int a[3][3] = { 
      {1, 2, 3}
      {4, 5, 6}
      {7, 8, 9} 
      };
      static int b[4][3] = { 
      {1, 2, 3}, 
      { }, 
      {4, 5} 
      };
      
      或
      int a[][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
      static int b[][3] = { {1, 2, 3}, { }, {4, 5} };
      
      数组a
      1 2 3 
      4 5 6
      7 8 9
      数组b
      1 2 3
      0 0 0
      4 5 0
      0 0 0
    

     

            j = 0   j = 1   j = 2
      i = 0  a[0][0] a[0][1] a[0][2]
      i = 1  a[1][0] a[1][1] a[1][2]
      i = 2  a[2][0] a[2][1] a[2][2]
    

     

      i<=j //上三角
      i>=j //下三角
      i==j //主对角线
      i+j==n-1//副对角线
    
  • 字符和字符串数组

     

      //一维字符数组
      char t[5] = { 'H', 'a', 'p', 'p', 'y' };
      static char s[6] = { 'H', 'a', 'p', 'p', 'y' };
      
      //字符串可以存放在一维字符数组中
      static char s[6] = { 'H', 'a', 'p', 'p', 'y', '\0' };
      //字符数组初始化:用字符串常量
      static char s[6] = { "Happy" };
      static char s[6] = "Happy";
      
      //数组长度 ≥ 字符串的有效长度 + 1
    
  • 统计数字字符个数

     

      #define MAXLINE 80
      char str[MAXLINE];
      printf("Enter a string: ");
      i = 0;
      while ((str[i] = getchar()) != '\n')
      {
        i++;
      }
      str[i] = '\0'; /* 输入结束符=>字符串结束符 */
      count = 0;
      for (i = 0; str[i] != '\0'; i++)
      {
        if (str[i] <= '9' && str[i] >= '0')
        {
            count++;
        }
      }
      printf("count = %d\n", count);
    
  • 凯撒密码

     

      //将明文中的所有字母都在字母表上向后偏移offset位后被替换成密文
      //当偏移量offset是2时,表示所有的字母被向后移动 2 位后的字母替换
      //所有的字母 A 将被替换成C,字母 B 将变为 D,…,字母 X 变成 Z,字母 Y 则变为 A,字母 Z 变为 B。
      #define M 26
      scanf("%d", &offset);
      if(offset >= M) 
      offset = offset % M; /* 移位效果相当于取其余数 */ 
      /* 加密 */
      for(i = 0; str[i] != '\0'; i++){ 
      if(str[i] >= 'A' && str[i] <= 'Z'){
      if((str[i] - 'A' + offset) < M) {
      	str[i] = str[i] + offset;
      }else{ /* 如果向后越界 */
      	str[i] = str[i] - (M - offset); /* 循环移位 */
      }
      }else if(str[i] >= 'a' && str[i] <= 'z'){
      if((str[i] - 'a' + offset) < M) {
      	str[i] = str[i] + offset;
      }else{
      	str[i] = str[i] - (M - offset); 
      }
      }
      }
    
  • 指针

     

      int *p, a = 3;
      p = &a; //把 a 的地址赋给 p,即 p 指向 a
    
  • 模拟开锁

     

      #include 
      int main(void)
      {
        int x = 5342;  /* 变量x用于存放密码值5342 */
        int *p = NULL; /* 定义整型指针变量p,NULL值为0,代表空指针 */
        p = &x;        /*将变量x的地址存储在p中 */
        /* 通过变量名x输出密码值*/
        printf("If I know the name of the variable, I can get it's value by name: %d\n ", x);
        /* 通过变量x的地址输出密码值 */
        printf("If I know the address of the variable is: %x, then I also can get it's value by address: %d\n", p, *p);
        return 0;
      }
    
  • 字符串压缩

     

      #include 
      #define MAXLINE 80
      void zip(char *p);
      int main(void)
      {
        char line[MAXLINE];
        printf("Input the string: ");
        gets(line);
        zip(line);
        puts(line);
        return 0;
      }
      
      void zip(char *p)
      {
        char *q = p;
        int n;
        while (*p != '\0')
        {
            n = 1;
            while (*p == *(p + n))
            {
                n++;
            }
            if (n >= 10)
            {
                *q++ = (n / 10) + '0';
                *q++ = (n % 10) + '0';
            }
            else if (n >= 2)
            {
                *q++ = n + '0';
            }
            *q++ = *(p + n - 1);
            p = p + n;
        }
        *q = '\0';
      }
    
  • 字符数组与字符指针

     

      char sa[ ] = "This is a string";//字符数组
      char *sp = "This is a string";//字符指针
      strcpy (sa, "Hello");
      sp = "Hello";
      //sp 可以直接赋值
      //sa = “Hello”; 非法
      //数组名是常量,不能对它赋值
    
  • gets/puts

     

      #include 
      int main()
      {
        char str[80];
        scanf("%s", str); //遇回车或空格输入结束,并自动将输入的一串字符和 '\0' 送入数组中
        printf("%s", str);
        printf("%s", "Hello");
        return 0;
      }
    

     

      #include 
      int main()
      {
        char str[80];
        gets(str); //遇回车输入结束,自动将输入的一串字符和 '\0' 送入数组中
        puts(str);
        puts("Hello");
        return 0;
      }
    
  • 字符串的复制

     

      static char str1[20];
      static char str2[20] = "happy";
      strcpy (str1, str2); //str1中 h a p p y \0
      strcpy (str1, “world”); //str1中: w o r l d \0
    
  • 字符串的连接

     

      #include "stdio.h"
      #include "string.h"
      int main(void)
      {
        char str1[80], str2[20];
        gets(str1);
        gets(str2);
        strcat(str1, str2);
        puts(str1);
        return 0;
      }
    
  • 字符串的比较

     

      //规则:按字典序(ASCII码序)
      //如果 str1 和 str2 相等,返回 0;
      //如果 str1 大于 str2 ,返回一个正整数;
      //如果 str1 小于 str2 ,返回一个负整数;
    

     

      # include 
      # include 
      int main (void) {
      int res;
      char s1[20], s2[20];
      gets (s1);
      gets (s2);
      res = strcmp (s1, s2);
      printf(“%d\n”, res);
      return 0;
      }
    
  • 字符串长度统计

     

      static char str[20] = "How are you?"
      strlen ("hello");//值是:5
      strlen (str);//值是:12
    
  • 求最小字符串长度

     

      int main ( ) 
      { int i, n;
      int x, min; 
      scanf ("%d", &n);
      scanf ("%d", &x);
      min = x; 
      for (i = 1; i < n; i++){
      scanf ("%d", &x);
      if (x < min)
      min = x; 
      }
      printf ("min is %d\n", min);
      return 0;
      }
      
    

     

      int main()
      { int i, n;
      char sx[80], smin[80]; 
      scanf ("%d", &n);
      scanf("%s", sx);
      strcpy (smin,sx); 
      for (i = 1; i < n; i++){
      scanf ("%s", sx);
      if (strcmp (sx, smin)<0) 
      strcpy (smin,sx);
      }
      printf ("min is %s\n", smin);
      return 0;
      }
    
  • 结构

     

      //单独定义:先定义一个结构类型,再定义一个具有这种结构类型的变量
      struct student {
      int num; /* 学号 */
      char name[10]; /* 姓名 */
      int computer, english, math; /* 三门课程成绩 */
      double average; /* 个人平均成绩 */
      };
    
  • 递归
  • 用递归函数实现求n!

     

      #include 
      double fact(int n);
      int main(void)
      {
        int n;
        scanf("%d", &n);
        printf("%f", fact(n));
        return 0;
      }
      double fact(int n) /* 函数定义 */
      {
        double result;
        if (n == 1 || n == 0) /* 递归出口 */
        {
            result = 1;
        }
        else
        {
            result = n * fact(n - 1);
        }
        return result;
      }
    
  • 将数字倒序输出

     

      void reverse(int num)
      {
        if (num <= 9)
        {
            printf("%d", num); /* 递归出口 */
        }
        else
        {
            printf("%d", num % 10);
            reverse(num / 10); /* 递归调用 */
        }
      }
    
  • 宏定义

     

      #include 
      #define MAX(a, b) a > b ? a: b
      #define SQR(x) x * x
    
  • 易错

     

      #define F(x) x - 2
      #define D(x) x*F(x)
      int main ( )
      {
      printf ("%d,%d", D(3), D(D(3))) ;
      return 0;
      }
    
  • 正解

     

      D (3) = x*F(x) 先用x替换展开
      	= x*x-2 进一步对F(x)展开,这里不能加括号
      	= 3*3-2 = 7 最后把x=3代进去计算
      D(D(3)) = D(x*x-2) 先对D(3)用x替换展开,
      		= x*x-2* F(x*x-2) 拿展开后的参数对D进一步进行宏替换
      		= x*x-2* x*x-2-2 拿展开后的参数对F进一步进行宏替换
      		= 3*3-2*3*3-2-2 = -13 最后把x=3代进去计算
      运行结果:7 -13
    
  • 长度单位转换

     

      #include 
      #define Mile_to_meter 1609       /* 1英里=1609米 */
      #define Foot_to_centimeter 30.48 /* 1英尺=30.48厘米 */
      #define Inch_to_centimeter 2.54  /* 1英寸=2.54厘米 */
      int main(void)
      {
        float foot, inch, mile; /* 定义英里,英尺,英寸变量 */
        printf("Input mile,foot and inch:");
        scanf("%f%f%f", &mile, &foot, &inch);
        printf("%f miles=%f meters\n", mile, mile * Mile_to_meter);
        /* 计算英里的米数 */
        printf("%f feet=%f centimeters\n", foot, foot * Foot_to_centimeter);   /* 计算英尺的厘米数 */
        printf("%f inches=%f centimeters\n", inch, inch * Inch_to_centimeter); /* 计算英寸的厘米数 */
        return 0;
      }
    
  • 文件操作
  • 暂无

更多好玩意请到主页瞧瞧
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇