利用 函数 ,不仅可以实现程序的模块化,使得程序设计更加简单和直观,从而提高了程序的易读性和可维护性,而且还可以把程序中经常用到的一些计算或操作编写成 通用函数 ,以供随时调用。
废话不说直接上操作
上图时模块化模块编程所需要用到的一些文件
我们把图上主文件(mian.c)头文件和源文件(hotel)都存放在同一个项目里(带dev后缀的)
/* usehotel.c -- 房间费率程序 */
/* 与程序清单9.10一起编译 */
#include <stdio.h>
#include "hotel.h" /* 定义符号常量,声明函数 */
int main(void)
{
int nights;
double hotel_rate;
int code;
while ((code = menu()) != QUIT)
{
switch (code)
{
case 1: hotel_rate = HOTEL1;
break;
case 2: hotel_rate = HOTEL2;
break;
case 3: hotel_rate = HOTEL3;
break;
case 4: hotel_rate = HOTEL4;
break;
default: hotel_rate = 0.0;
printf("Oops!\n");
break;
}
nights = getnights();
showprice(hotel_rate, nights);
}
printf("Thank you and goodbye.\n");
return 0;
}
这是我们的主文件,里边主要用到了我们《stdio.h编译器自带的数据库》跟我们自行编写的一个在定义头文件(个人叫他在定义的函数库)
/* hotel.c -- 酒店管理函数 */
#include <stdio.h>
#include "hotel.h"
int menu(void) //获取一个范围内的数字(1~5)--菜单选择
{
int code, status;
printf("\n%s%s\n", STARS, STARS);
printf("Enter the number of the desired hotel:\n");
printf("1) Fairfield Arms 2) Hotel Olympic\n");
printf("3) Chertworthy Plaza 4) The Stockton\n");
printf("5) quit\n");
printf("%s%s\n", STARS, STARS);
while ((status = scanf("%d", &code)) != 1 ||
(code < 1 || code > 5))
{
if (status != 1)
scanf("%*s"); // 处理非整数输入
printf("Enter an integer from 1 to 5, please.\n");
}
return code;
}
int getnights(void) //获取到一个整数--入住天数
{
int nights;
printf("How many nights are needed? ");
while (scanf("%d", &nights) != 1)
{
scanf("%*s"); // 处理非整数输入
printf("Please enter an integer, such as 2.\n");
}
return nights;
}
void showprice(double rate, int nights) //获取到价格
{
int n;
double total = 0.0;
double factor = 1.0;
for (n = 1; n <= nights; n++, factor *= DISCOUNT)
total += rate * factor;
printf("The total cost will be $%0.2f.\n", total);
}
这个是源文件
/* hotel.h -- 符号常量和 hotel.c 中所有函数的原型 */
#define QUIT 5
#define HOTEL1 180.00
#define HOTEL2 225.00
#define HOTEL3 255.00
#define HOTEL4 355.00
#define DISCOUNT 0.95
#define STARS "**********************************"
// 显示选择列表
int menu(void);
// 返回预订天数
int getnights(void);
// 根据费率、入住天数计算费用
// 并显示结果
void showprice(double rate, int nights);
最后一个就是我们自定义的一个头文件
这是运行结果
里边用到了一个switch函数,提供给我们选择函数里边定义的酒店选项,在1~5之间可以输入有效值,超出有效值系统会让我们重新输入知道输入正确选项为止。
输入正确选项之后输入你要在该酒店所入住的天数,系统会按照所给天数计算价格然后给我们呈现。
这是面板
接下来进入实操
pace1
我用的时dvec++这款编译器
新建一个项目
选择第二个,然后是c项目
紧接着创建完一个项目,在这个项目之内点击创建新项目把主文件,头文件,源文件一次创建即可
实现自己想要的功能。