zoukankan      html  css  js  c++  java
  • C语言基础05

    二维数组的定义:

    数据类型 数组名称 [ 常量表达式1 ] [ 常量表达式2 ] = {.....}

    int a[ 2 ][ 3 ] ={

      {4,5,6},

      {7,8,0},                 //或者{7} 后面不写8和9 ,系统会默认的帮你添加0就是这样:{7,0,0}

    };

    OR:

    int b[ 3 ][ 2 ] ={3,87,43,66,82,11,34 };

    OR:

    int b[][ 2 ] ={3,87,43,66,82,11,34 };    //行数可以不写,但是列数不写或者2个都不写就不行.

    // int a[][] = {1,2,3,4,5,6,7};  错误.

    // int a[2][] = {1,2,3,4,5,6,7};错误.

     字符串数组

    char 数组名称 [字符串个数][每个字符串内存中允许存放的最大值] ={....}

    char  str[ 3 ][ 20 ] ={"ipad","ipod","iphone"};

    字符串数组本质上是一个二维数组,访问某个字符串使用数组名称[第一维下标].

    每个字符串的长度不能超过第二维度的长度-1。 

     比如说:

    char str2[ 3 ][ 20 ] ={"luoshuailuotingluomama","ipod","ipad"};

    第二维度为20,20-1 =19,但是第一个字符串就超过了19.

        char str2[ 3 ][ 20 ] ={"luoshuailuotingluomamadddddddssssssss","ipod","ipad"};     //不会报错,但是会警告.

         for (int i =0 ; i < 3; i++ ) {

            printf("The end of Result :%s ",str2[i]);

        }

    思考一个问题 :  

    创建一个字符串数组,对字符串 (英⽂)从小到大排序 

      char  str[5][20] ={"ipad","ipod","iphone","main","luoshuai"};

      char temp[] ={0};

      int length =strlen(str);

      for(int i =0 ;i < length-1 ; i++ ){  

        for(int j =0 ;j<length-i-1;j++){

          if(  strcmp( str[j] ,str[j+1] )  > 0 ){  

             strcopy(temp,str[j]);

             strcopy(str[j],str[j+1]);

             strcopy(str[j+1],temp);

          }

    }

    }

    for(int i =0 ; i < length;  j++){  

      printf("The end of Result : %s ",str[i]);

    }

    选择排序法  

        他的算法就是:将第一个与后面所有数字比较,如果找到比它还小的,两两数字交换.一轮下来最小值找到了.

     第二轮从第二个数字开始,与上面步骤相同.

    int array[7] ={23,36,45,57,69,35,88};

     for ( int i = 0; i < 7 ; i++) {

             for (int j = i+1 ; j < 7; j++) {

                   if (array[i]  > array[j]) {

                      int temp = array[i];

                 array[i] =array[j];

                         array[j]  =temp;

                 }

             }

         }

    优化版:可以省去很多不必要的循环:

    for ( int i = 0;i < 6;i++) {     //外层循环 控制趟数,为个数减1. i= 0时候

     int flag = 0 ;  //设置一个标记,如果两辆数字进行交换,我们就设置为1,

      for (int j = i+1 ; j < 7; j++) {    //从第二个数,第三个..数分别与i=0数字比较.

     if (array[i]  > array[j]) {     //i=0 分别与后面所有的比较一次,交换. j从1 开始 j<7  刚好内部循环6次.

       int temp = array[i];        //i=1的时候,j从下标2开始 j< 7 刚好循环5次

       array[i] =array[j];

       array[j]  =temp;

       flag = 1;

       }

    }

      //printf("循环的次数为:%d ",(i+1));

     if( !flag ){

       break;

     }

     }

      for (int i = 1; i< 7 ; i++) {    //输出数字.

                 printf("The end  of Result : %d ",array[i]);

        }

  • 相关阅读:
    bootstrapValidator表单验证插件
    sublime自动保存(失去焦点自动保存)
    js、jquery实现放大镜效果
    mysql 添加索引语句
    mybatis sql语句中的foreach标签
    android ListView 刷新卡顿问题
    JFrame 桌面右下角弹窗
    取没有date的邮件发送时间
    java 判断图片是否损坏
    java 后台poi导入导出Excel到数据库
  • 原文地址:https://www.cnblogs.com/liruoxuan/p/4071847.html
Copyright © 2011-2022 走看看