一、函数讲解
1、函数设计的语法
函数就是方法,函数就是功能,对数据进行操作:
新增数据
修改数据
删除数据
查询数据
自定义函数的设计:
【1】无参数无返回值
类型 函数名()
void 函数名( )
调用:
show();
示例:
#include <stdio.h>
// 打印欢迎信息
void greet() {
printf("Hello, welcome to the program!\n");
}
int main() {
greet(); // 调用无参数无返回值函数
return 0;
}
【2】有参数无返回值
void 函数名(形参1 , 形参2 , 形参3 … )
{
语句组;
}
示例:
#include <stdio.h>
// 打印两个数的和
void printSum(int a, int b) {
int sum = a + b;
printf("The sum of %d and %d is %d\n", a, b, sum);
}
int main() {
printSum(5, 7); // 调用有参数无返回值函数
return 0;
}
【3】无参数有返回值
返回值类型 函数名( )
{
语句组;
}
返回值类型 :int char 等等
示例:
#include <stdio.h>
#include <time.h>
// 获取当前小时数(0-23)
int getCurrentHour() {
time_t now;
time(&now);
struct tm *local = localtime(&now);
return local->tm_hour;
}
int main() {
int hour = getCurrentHour(); // 调用无参数有返回值函数
printf("Current hour is: %d\n", hour);
return 0;
}
【4】有参数有返回值
返回值类型 函数名(形参1 , 形参2 , 形参3 … )
{
语句组;
}
返回值类型 :int char 等等
示例:
#include <stdio.h>
// 计算两个数的最大值
int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int x = 10, y = 20;
int maximum = max(x, y); // 调用有参数有返回值函数
printf("The maximum between %d and


1009

被折叠的 条评论
为什么被折叠?



