用户名: 密码: 验证码: gdcode 注册

C语言程序应用举例

时间:2007-06-14 来源: 作者: 【字体: 减小 增大点击: 收藏 | 投稿
  

这是一个递归函数调用的例子。程序中函数forward_and_backwards()的功能是显示一个字符串后反向显示该字符串。
[例4-17]计算1~7的平方及平方和。
#include<stdio.h>
#include<math.h>
voidheader();/*函数声明*/
voidsquare(intnumber);
voidending();
intsum;/*全局变量*/
main()
{
intindex;
header();/*函数调用*/
for(index=1;index<=7;index)
square(index);
ending();/*结束*/
}
voidheader()
{
sum=0;/*初始化变量"sum"*/
printf("Thisistheheaderforthesquareprogram\n;\n")
}
voidsquare(intnumber)
{
intnumsq;
numsq=number*numbe;r
sum=numsq;
printf("Thesquareof%dis%d\,nn"umber,numsq);
}
voidending()
{
printf("\nThesumofthesquaresis%d,\ns"um);
}
运行程序:
RUN¿
Thisistheheaderforthesquareprogram
Thesquareof1is1

财管家.园.fs119.net


Thesquareof2is4
Thesquareof3is9
Thesquareof4is16
Thesquareof5is25
Thesquareof6is36
Thesquareof7is49
Thesumofthesquaresis140
这个程序打印出1到7的平方值,最后打印出1到7的平方值的和,其中全局变量sum在多个
函数中出现过。
全局变量在header中被初始化为零;在函数square中,sum对number的平方值进行累加,也就是说,每调用一次函数square和sum就对number的平方值累加一次;全局变量sum在函数
ending中被打印。
[例4-18]全局变量与局部变量的作用。
#include<stdio.h>
voidhead1(void);
voidhead2(void);
voidhead3(void);
intcount;/*全局变量*/
main()
{
registerintindex;/*定义为主函数寄存器变量*/
head1();
head2();
head3();
for(index=8;index>0;index--)/*主函数"for"循环*/
{
intstuff;/*局部变量*/
/*这种变量的定义方法在TurboC中是不允许的*/
/*stuff的可见范围只在当前循环体内*/
财管家园,fs119.net

for(stuff=0;stuff<=6;stuff)
printf("%d",stuff);
printf("indexisnow%d\,n"index);
}
}
intcounter;/*全局变量*/
/*可见范围为从定义之处到源程序结尾*/
voidhead1(void)
{
intindex;/*此变量只用于head1*/
index=23;
printf("Theheader1valueis%d\,n"index);
}
voidhead2(void)
{
intcount;/*此变量是函数head2()的局部变量*/
/*此变量名与全局变量count重名*/
/*故全局变量count不能在函数head2()中使用*/
count=53;
printf("Theheader2valueis%d\,n"count);
counter=77;
}
voidhead3(void)
{
printf("Theheader3valueis%d\,nc"ounter);
}
运行程序:
RUN¿
Theheaderlvalueis23
Theheader2valueis53
Theheader3valueis77
0123456indexisnow8
0123456indexisnow7
0123456indexisnow6
0123456indexisnow5
0123456indexisnow4
0123456indexisnow3
0123456indexisnow2
0123456indexisnow1
该程序的演示帮助读者来了解全局变量、局部变量的作用域,请仔细理解体会。 财管 家园 fs119.net

财.软联盟.fs119.net


文章摘自网络,如有侵权,请与我们联系.
数据统计中!!
上一篇:一维数组
下一篇:C语言的预处理程序与注释

精品课程推荐


相关文章
  • C语言的预处理程序与注释 2007-06-14 17:47:57
  • C语言程序应用举例 2007-06-14 17:47:56
  • 一维数组 2007-06-14 17:47:46
  • 二维数组 2007-06-14 17:47:45
  • 多维数组 2007-06-14 17:47:45
  • 数组的初始化 2007-06-14 17:47:44

  • 用户名: 密码: 匿名? 注册