环境:vistal studio 2010 sp1,win7 x86.
1.自定义 和 声明
#include<stdio.h>
//引入系统头文件stdio.h包含的函数(库函数),为下面调用做准备
main()
{
float add(float x,float y);//声明add()函数,为下面调用做准备,声明不占内存
float a,b,c;
scanf("%f,%f",&a,&b);//使用头文件stdio.h包含的函数scanf().作为语句直接使用(1)
c=add(a,b);//调用自定义函数add().这是一个函数表达式,函数的返回值参与表达式运算(2)
printf("sum is %f",c);//使用头文件stdio.h包含的函数printf()
}
//用户自定义函数:add()函数.函数定义占用内存.若在主函数main()之前,则不用额外声明
float add(float x,float y)//函数首部(头部)
//函数体
{
float z;
z=x+y;
return z;
}
运行结果:
2.也可作为参数调用
3.调用 系统头文件内的函数
#include<stdio.h>
#include<math.h>
main()
{
double x=2.0,y=3.0 ,z;
z=pow(x,y); //指数
printf("%.1f/d",z);
}
#include<stdio.h>
#include<math.h>
//this program calculate a square root
main()
{
double question=-9.0,answer=sqrt(question);
if(question<0)
printf("error: sqrt return %.2f\n",answer);
else
printf("the square root of %.2f is %.2f\n",question,answer);
}
4.自定函数并调用
#include<stdio.h>
double power(double x ,double y);
main()
{
double x=2.0,y=3.0 ,z;
z=power(x,y); //指数
printf("%.1f \n",z);
}
double power(double x ,double y)
{
double z=1;
while (y>0)
{
z*=x;
y--;
}
return z;
}
#include<stdio.h>
//this program calculate a square root
main()
{
int sqrt_0(int question);
int question=50,answer=sqrt_0(question);
if(question<0)
printf("error: sqrt return %d\n",answer);
else
printf("the square root of %d is %d\n",question,answer);
}
int sqrt_0(int question)
{
int temp=question/2;
while (temp--)
{
if (temp*temp==question)
return temp;
}
return -1;
}
5.main函数
main不是关键字,main函数是系统调用的入口,不同环境可能有着不同的入口函数名.
因此变量名设置为main是合法的