前序:
控制台输出结果:
the first experssion is true.
本节课导图:
函数的引申:
int main(int argc, const char * argv[]) {
// insert code here...
printf("wyy has done as much as iOS as I could fit into 5 days\n");
printf("Mike has done as much as C as I could fit into 6 days\n");
printf("Jack has done as much as OC as I could fit into 15 days\n");
printf("Lisa has done as much as Python as I could fit into 10 days\n");
printf("Lucy has done as much as Cocoa as I could fit into 7 days\n");
return 0;
}
可以看到,我们需要输入大量的文字代码,是不是很烦人?其中是否有很多重复性的语句?如果有,我们是否可以提取出来一个函数,来完成这个功能?答案是可以的。
void congratulateStudent (char *student, char *course, int numDays)
{
printf("%s has done as much as %s as I could fit into %d days\n",student,course,numDays);
}
int main(int argc, const char * argv[]) {
// insert code here...
congratulateStudent("wyy", "iOS", 5);
congratulateStudent("Lucy", "OC", 4);
congratulateStudent("Jack", "Python", 7);
return 0;
}
递归调用
void singSong (int num)
{
if (num == 0) {
printf("歌曲结束\n");
}else{
printf("%d个歌曲\n",num);
int oneFewer = num - 1;
singSong(oneFewer);//递归调用
printf("%d歌曲正在播放\n",num);
}
}
int main(int argc, const char * argv[]) {
// insert code here...
singSong(4);
return 0;
}
控制台结果:
4个歌曲
3个歌曲
2个歌曲
1个歌曲
歌曲结束
1歌曲正在播放
2歌曲正在播放
3歌曲正在播放
4歌曲正在播放
Program ended with exit code: 0
返回函数值
float triangleArea(float a, float b,float h)
{
float triangleArea = a * b * h;
printf("triangleArea is %f.\n",triangleArea);
return triangleArea;
}
int main(int argc, const char * argv[]) {
// insert code here...
triangleArea(2, 3, 4);
return 0;
}
全局变量和静态变量
//float lastTemprature;//全局变量
static float lastTemprature;//静态变量
float fahrenheitFromCelsius(float cel)
{
lastTemprature = cel;
float fahr = cel *1.8+32.0;
printf("%f Celsius is %f Fahrenheit\n",cel,fahr);
return fahr;
}
int main(int argc, const char * argv[]) {
// insert code here...
float freezeInC = 0;
float freezeInF = fahrenheitFromCelsius(freezeInC);
printf("the lastTemprature %f \n",freezeInF);
return EXIT_SUCCESS;
}
练习题:
已知三角形内角和一定是180度,试创建一个新项目,类型为基于C语言的command Line Tool名称为 Triangle。在main.c编写一个函数,参数是某两个内角的角度,返回值一个剩下的第三个内角的角度。
答案见下一章,写对者红包奖励哦。欢迎初学者多多参与。