第53課自定義函數
·函數定義
return_type function_name([datatype1 arg1],[datatype arg2],[...])
{
//函數體
}
·函數三要素
·傳回值類型
·函數名
·參數清單
·自定義函數的完整寫法
#include <stdio.h>
//函數原型
int sum(int,int);
int main()
{
...
}
//函數定義
int sum(int num1, int num2)
{
//函數實作的代碼
}
最重要的是函數的三要素
不要先想如何去完成什麼功能。
傳回值+函數名+參數
九層之台始于累土!!!函數就是不斷地複用,越往後越熟練。
一、典型自定義函數
//代碼******************************
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//函數原型
void calcCircle(); //計算圓面積
void calcRectangle(); //計算矩形面積
/*
計算圓的面積(函數實作)
*/
void calcCircle()
{
double radius;
double s;
printf("請輸入圓的半徑:");
scanf("%lf",&radius);
s = 3.14 * pow(radius, 2);
printf("半徑為%.2lf的圓面積為:%.2lf\n", radius, s);
}
void calcRectangle()
{
double width;
double height;
double s;
printf("請輸入矩形的長:");
scanf("%lf",&width);
printf("請輸入矩形的寬:");
scanf("%lf",&height);
s = width*height;
printf("長為%.2lf,寬為%.2lf的矩形面積為:%.2lf\n", width, height,s);
}
int main()
{
/*
三種圖形的面積計算公式如下:
圓:s = PI*r*r;
矩形: s = width * height;
三角型: s = width * height /2;
使用函數分别實作三種圖形的面積計算,列印計算結果
*/
//書寫函數的步驟:完成函數的三要素
//誤區:不要一開始就去考慮如何完成某個功能
calcCircle(); //調用計算圓面積的函數
calcRectangle(); //調用計算矩形面積的函數
//需要傳回值麼?
//函數名是什麼?
//需要給這個函數參數麼?
}
//代碼******************************
二、有傳回值的函數
·計算1-100偶數和
//代碼********************************************************
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//函數原型
int calcSum(); //求1-100之間的偶數和,傳回值為int型(不是void了)
//函數定義
int calcSum()
{
//1-100之間的偶數和
int sum = 0;
int i = 1;
for(i = 1; i <= 100; i++)
{
if(i % 2 ==0) //判斷是否為偶數
sum += i;
}
//将計算好的結果傳回
return sum;
}
//調用
//如果函數有傳回值,調用時,記得使用對應類型的變量來接受!
int main()
{
int sum = calcSum();
printf("1-100之間的偶數和為:%d\n",sum);
}
//代碼********************************************************
三、有傳回值的函數
//代碼********************************************************
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
書寫函數實作數組元素的查找,要求傳回找到的元素下标
*/
//1、傳回值:元素下表
//2、函數名
//3、函數參數
//函數原型
//函數定義
//調用函數
int search();
int search()
{
int nums[] = {34,56,7,3,2};
int i ;
//要查找的數字,所查找數字的下标,沒找到index為-1
int searchNum, searchIndex = -1;
printf("請輸入要查找的整型數字:");
scanf("%d", &searchNum);
for(i = 0; i < 5; i++)
{
if(searchNum == nums[i]) //*(nums + i )
{
searchIndex = i; //記錄下查找到的下标
break;
}
}
return searchIndex;
}
int main()
{
int a;
a = search();
printf("找到的元素的下标是:%d\n",a);
return 0;
}
四、總結:
void function(); //函數原型
void function() //函數定義
function(); //調用函數
先思考:
傳回值
函數名
函數參數