C入门系列:第一章 基本类型
C入门系列:第二章 字符串
C入门系列:第三章 函数
C入门系列:第四章 数组和指针
C入门系列:第五章 数据存储类别和内存管理
C入门系列:第六章 文件输入/输出
C入门系列:第七章 结构和其他数据形式
C入门系列:第八章 C预处理器和C库
1 函数
#include<stdio.h>
void pound(int n);
int main(void) {
int times = 5;
char ch = '!';
float f = 6.0f;
pound(times);
pound(ch);
pound(f);
return 0;
}
void pound(int n) {
while (n-- > 0) {
printf("#");
}
printf("\n");
}
2 引入自定义头文件
hotel.h
#define QUIT 5
#define HOTEL1 180.00
#define HOTEL2 225.00
#define HOTEL3 255.00
#define HOTEL4 355.00
#define DISCOUNT 0.95
#define START "*****************"
int menu(void);
int getnights(void);
void showprice(double rate, int nights);
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;
break;
}
nights = getnights();
showprice(hotel_rate, nights);
}
return 0;
}
int menu(void) {
int code, status;
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;
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;
}
}