头文件的使用
** 把函数原型和常量定义放在一个头文件中是一个很好的编程习惯。
例子:
假设需要管理4个连锁的旅馆。对于预定住宿时间超过一天的人来说,第1天的收费是第1天的95%,而第3天的收费则是第2天的95%,等待。编写一个程序,对于指定的旅馆和住宿天数可以计算出收费总额。同时程序中要实现一个菜单,从而允许用户反复进行数据输入直到选择退出。
源码:
/* usehotel.c -- 旅馆房间收费程序 */
#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;
}
/* hotel.c -- 旅馆管理函数 */
#include <stdio.h>
#include "hotel.h"
int menu(void)
{
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 Stockeon/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 need? ");
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 80.00
#define HOTEL2 125.00
#define HOTEL3 155.00
#define HOTEL4 200.00
#define DISCOUNT 0.95
#define STARS "*********************"
//输出选项列表
int menu(void);
//返回预定的天数
int getnights(void);
//按饭店的星级和预定的天数计算价格并显示
void showprice(double, int);
运行示例:
******************************************
Enter the number of the desired hotel:
1) Fairfield Arms 2) Hotel Olympic
3) Chertworthy Plaza 4) The Stockeon
5) quit
******************************************
3
How many nights are need? 1
The total cost will be $155.00.
******************************************
Enter the number of the desired hotel:
1) Fairfield Arms 2) Hotel Olympic
3) Chertworthy Plaza 4) The Stockeon
5) quit
******************************************
4
How many nights are need? 3
The total cost will be $570.50.
******************************************
Enter the number of the desired hotel:
1) Fairfield Arms 2) Hotel Olympic
3) Chertworthy Plaza 4) The Stockeon
5) quit
******************************************
5
Thank you and goodbye.
程序特色:通过检测scanf()函数的返回值来跳过输入的非数字数据,并前使用scan("%*s")来跳至下一空白字符。在scanf()中,把*放在%和说明符之间使函数跳过相应的输入项目,即相当于没有输入。
考察代码:
while (scanf("%d", &nights) != 1)
{
scanf("%*s");
printf("Please enter an integer, such as 2./n");
}
这段代码运用了C的两个运算规则:逻辑表达式从左向右运算,并且一旦结果明显为假,运算会立即停止。在本例中,只有确定scanf()已成功读取了一个整形数组后,变量code才会被检查。
本篇文章来源于 黑客基地-全球最大的中文黑客站