C语言

源代码分门别类管理,通过头文件。

放置一些函数声明,变量声明,常量定义,宏定义。

hotel.h

#ifndef HOTEL_H_INCLUDED
#define HOTEL_H_INCLUDED

#define HOTEL1 872.0 // 各家酒店的默认房费
#define HOTEL2 1838.0 // 各家酒店的默认房费
#define HOTEL3 789.0 // 各家酒店的默认房费
#define HOTEL4 1658.0 // 各家酒店的默认房费
#define DISCOUNT 0.95 // 折扣率


// 菜单函数:显示菜单选项,接收并返回用户的输入
int Menu(void);

// 返回用户预订的天数
int GetNights(void);

// 根据入住的天数显示最终需要支付的金额
double ShowPrice(int choice,int nights);
#endif // HOTEL_H_INCLUDED

hotel.c

#include <stdio.h>
// 自定义的头文件用双引号
#include "hotel.h"

char hotelNames[4][50] = {
    "贝罗酒店","香榭丽舍酒店","阿斯图里亚斯酒店","斯克里布酒店"
};

int Menu(void) {
    int choice; // 用户的选择
    int i;
    printf("请选择入住的酒店:
");
    for (i = 0; i< 4;i++) {
        printf("%d、%s
",i+1,hotelNames[i]); // 写完就去main中测试一下
    }

    printf("5、退出程序
");

    printf("请输入您的选择:");

    int result = scanf("%d",&choice);

    // 判断是否合法
    while ( result !=1 || choice < 1 || choice >5 ) {
        if (result != 1) {
            scanf("%*s"); // 消除错误的输入
            // fflush(stdin);
        }

        printf("必须输入1-5之间的整数:");
        result = scanf("%d",&choice);
    }



    return choice;
}

int GetNights(void) {
    int nights;

    printf("先生、女士,请输入要入住的天数:");

    int result = scanf("%d",&nights);

    // 判断是否合法
    while ( result !=1 || nights < 1) {
        if (result != 1) {
            scanf("%*s"); // 消除错误的输入
            // fflush(stdin);
        }

        printf("必须输入大于1的整数!
");
        printf("先生、女士,请输入要入住的天数:");
        result = scanf("%d",&nights);
    }

    return nights;
}

double ShowPrice(int choice,int nights) {
    double hotelPrice;
    double totalPrice = 0;
    if (choice == 1) {
        hotelPrice = HOTEL1;
    }

    if (choice == 2) {
        hotelPrice = HOTEL2;
    }

    if (choice == 3) {
        hotelPrice = HOTEL3;
    }

    if (choice == 4) {
        hotelPrice = HOTEL4;
    }

    int i;
    for (i = 0 ;i<nights ;i ++ ) {
        if (i == 0) {
            totalPrice = hotelPrice * DISCOUNT;
        } else {
            totalPrice += hotelPrice * DISCOUNT;
        }

        hotelPrice = hotelPrice * DISCOUNT;
    }

    return totalPrice;

}

main.c

#include <stdio.h>
#include <stdlib.h>
#include "hotel.h"  // 最好引入一下头文件
extern char hotelNames[4][50]; // 声明为外部变量

int main()
{
    int choice;
    int nights;
    double totalPrice;
    // 用户输入入住的酒店和天数,程序计算出对应的金额
    // 1.显示菜单 - 封装成函数
    choice = Menu();

    if (choice > 0 && choice <5) {
        printf("当前用户选择的是:%s
",hotelNames[choice-1]); // 多遇到一些错误,在错误中成长。将顺序思维,改为模块思维。
    }

    if (choice == 5) {
        printf("欢迎使用本系统,再见。
");
        exit(0);
    }


    nights = GetNights();
    if (nights > 0) {
        printf("当前用户选择入住%d天
",nights); // 多遇到一些错误,在错误中成长。将顺序思维,改为模块思维。
    }

    // 2.计算过程
    totalPrice = ShowPrice(choice,nights);
    printf("您入住的酒店是:%s 	 入住天数: %d 	 总费用: %0.2f 
",hotelNames[choice-1],nights,totalPrice);

    printf("欢迎使用本系统,再见。
");
    return 0;
}

头文件有约束作用。可以重复使用。

原文地址:https://www.cnblogs.com/jiqing9006/p/8296556.html