第一章——导言(2)

来源:互联网 发布:淘宝二手货市场 编辑:程序博客网 时间:2024/06/05 02:10

一、数组

#include <stdio.h>


 int main()
{  
  int c, i, nwhite, nother;
  int ndigit[10];

  nwhite = nother = 0;
  for (i = 0; i < 10; i++)
   ndigit[i] = 0;

  while ((c = getchar())!=EOF)
  if (c >= '0' && c <= '9')
   ++ndigit[c - '0'];                                   //将输入的各个数字出现的次数存入数组中
  else if (c == ' ' || c == '\n' || c == '\t')
   ++nwhite;
  else
   ++nother;

  printf("digits = ");
  for (i = 0; i < 10; i++)
   printf("  %d", ndigit[i]);
  printf(",white space = %d,other = %d", nwhite, nother);

 
 return 0;
}

    在代码  ++ndigit[c - '0'];  中,'0'由char转化为int类型,然后令c减该数,因为‘0’,‘1’,‘2’是连续递增的值,所以这样的运算成立。


二、函数

#include <stdio.h>

int power(int m, int n);             //用于计算整数m的n次幂

int main(){
 int i;
 for (i = 0; i < 10; i++)
  printf("%3d %3d %6d\n", i, power(2, i), power(-3, i));
 return 0;
}

int power(int base, int n)
{                                         //求底数的n次幂,其中n>=0
 int i, p;
 p = 1;
 for (i = 1; i <= n; i++)
  p = p*base;
 return p;

}


三、参数——传值调用

int power(int base, int n)
{
 int p;
 for (p = 1; n > 0; --n)
  p = p*base;
 return p;
}//参数n作为临时变量随for循环递减,避免了额外引入变量


四、字符数组

#include <stdio.h>

#define MAXLINE 1000     //允许的输入行的最大长度

int getline(char line[], int maxline);
void copy(char to[], char from[]);

int main(){            //打印最长的输入行
 int len;                //当前行长度
 int max;                //目前为止发现的最长行长度
 char line[MAXLINE];     //当前的输入行
 char longest[MAXLINE];  //用于保存最长的行

 max = 0;
 while ((len = getline(line,MAXLINE))>0)
 if (len > max){
  max = len;
  copy(longest, line);
 }
 if (max > 0)               //存在这样的行
  printf("%s", longest);
 return 0;
}

int getline(char s[], int lim)    
{//将一行读入到s,并返回长度
 int c, i;
 
 for (i = 0; i < lim - 1 && (c = getchar()) != EOF&&c != '\n'; i++)
  s[i] = c;
 if (c == '\n')
  s[i++] = c; //注意这里的自增
 s[i] = '\0';
 
 return i;
}

void copy(char to[], char from[])
{//将from复制到to,这里假定to足够大
 int i = 0;
 while ((to[i] = from[i]) != '\0')
  ++i;
}

     getline()把字符‘0’(即空字符,值为0)插入到它创建的数组末尾。


五、外部变量与作用域

     1、在对外部变量赋值的函数返回后,这些变量仍将保持原来的值不变

     2、在每个需要访问外部变量的函数中,必须声明相应的外部变量,此时说明其类型。声明时可以用extern语句显式声明,也可以通过上下文隐式声明。

     3、外部变量的定义出现在使用它的函数前,就没必要使用extern声明。

     4、通常将变量和函数的extern声明放在一个单独的文件中(习惯上称之为头文件)












0 0
原创粉丝点击