C语言多源代码文件

编译多源代码文件程序

在进行大型项目时,为避免在main()中写出函数原型,可将函数原型放在其他文件中,通过头文件进行管理。另外,预处理定义的符号常量放在头文件中便于后续维护。

这里通过一个案例来理解,假设要管理 4 家酒店的客房服务,每家酒店的房价不同,但是每家酒店所有房间的房价相同。对于预订住宿多天的客户,第2天的房费是第1天的95%,第3天是第2天的95%,以此类推(暂不考虑这种策略的经济效益)。设计一个程序让用户指定酒店和入住天数,然后计算并显示总费用。同时,程序要实现一份菜单,允许用户反复输入数据,除非用户选择退出。

  1. 酒店管理程序
c 复制代码
// 酒店管理函数
#include <stdio.h>
#include "hotel.h"
/*菜单函数*/
int menu()
{
    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);
}
  1. 酒店常量以及函数原型
c 复制代码
/* 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);
  1. 用户主函数
c 复制代码
// 房间费率计算程序
#include <stdio.h>
#include "hotel.h"

int main()
{
    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;
}
相关推荐
南猿北者2 小时前
Cmake学习笔记
笔记·学习·策略模式
diablobaal3 小时前
云计算学习100天-第26天
学习·云计算
测试老哥4 小时前
pytest+requests+allure自动化测试接入Jenkins学习
自动化测试·软件测试·学习·测试工具·职场和发展·jenkins·pytest
diablobaal8 小时前
云计算学习100天-第21天
学习
好望角雾眠19 小时前
第一阶段C#基础-10:集合(Arraylist,list,Dictionary等)
笔记·学习·c#
艾伦~耶格尔19 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
星仔编程19 小时前
python学习DAY46打卡
学习
大霞上仙20 小时前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
yatingliu20191 天前
HiveQL | 个人学习笔记
hive·笔记·sql·学习
武当豆豆1 天前
C++编程学习(第25天)
开发语言·c++·学习