C primer plus练习题以及案例笔记

关键词以及函数等等用法笔记

\n 换行
\a 警报
\b 退格
\f 换页
\r 回车
\t 水平制表符
\v 垂直制表符
\\ 反斜杠
\' 单引号
\" 双引号
\? 问号
\Ooo 八进制值
\xhn 十六进制值
%d		是用来指定输入和输出时的数据类型和格式,表示“以十进制整数的形式输出”。
%a 		浮点数、十六进制数字和p-记数法(C99)
%A    浮点数、十六进制数字和p-记法(C99)
%c    一个字符(char)
%C 		一个ISO宽字符
%d    有符号十进制整数(int)(%ld、%Ld:长整型数据(long),%hd:输出短整形。) 
%e    浮点数、e-记数法
%E    浮点数、E-记数法
%f    单精度浮点数(默认float)、十进制记数法(%.nf 这里n表示精确到小数位后n位.十进制计数)
%g    根据数值不同自动选择%f或%e.
%G    根据数值不同自动选择%f或%e.
%i 		有符号十进制数(与%d相同)
%o    无符号八进制整数
%p    指针
%s    对应字符串char*(%s == %hs == %hS 输出 窄字符)
%S	    对应宽字符串WCAHR*(%ws == %S 输出宽字符串)
%u    无符号十进制整数(unsigned int)
%x    使用十六进制数字0f的无符号十六进制整数 
%X    使用十六进制数字0f的无符号十六进制整数
%%    打印一个百分号
%zd		sizeof strlen返回类型

转换修饰符

标志	五种标志将在后面的表2中说明,可以使用零个或者多个标志,示例: “%-10d”

数字	字段宽度的最小值。如果字段不能容纳要打印的数或者字符串,系统会使用更宽的字段示例: “%4d”,“%10s”
.数字	精度 对于%e,%E和%f转换,是将要在小数点的右边打印的数字的位数。对于%g和%G转换,是有效数字的最大位数。对于%s转换,是将要打印的字符的最大数目。对于整数转换,是将要打印的数字的最小位数。如果必要,要使用前导0来达到位数。只使用"."表示其后跟随一个0,所以%.f和%.0f相同。示例: “%5.2f”表示打印一个浮点数,它的字段宽度为5个字符,小数点后有两个数字

h	和整数转换说明符一起使用,表示一个short int或unsigned short int类型数值。示例: “%hu”, “%hx”, “%6.4hd”
hh	和证书转换说明符一起使用,表示一个signed char或unsigned char类型数值
j	和整数转换说明符一起使用,表示一个intmax_t或uintmax_t值示例: “%jd”,"%8jx"
l	和整数转换说明符一起使用,表示一个long int或unsigned long int类型值
ll	和整数转换说明符一起使用,表示一个long long int或unsigned long long int类型值(C99)示例: “%lld”,"%8llu"
L	和浮点数转换说明符一起使用,表示一个long double值示例: “%Lf”, “%10.4Le”
t	和整数转换说明符一起使用,表示一个ptrdiff_t值(与两个指针之间的差相对应的类型)(C99)。示例: “%td”, “%1ti”
z	和整数转换说明符一起使用,表示一个size_t值(sizeof返回的类型)(C99)。示例: “%zd”,"%12zx"


-	项目左对齐,即,会把项目打印在字段的左侧开始处。示例: “%-20s”
+	有符号的值若为正,则显示带加号的符号;若为负,则显示带减号的符号。示例: “%+6.2f”
(空格)	有符号的值若为正,则显示时带前导空格(但是不显示符号);若为负,则带减号符号。+标志会覆盖空格标志。示例: “% 6.2f”
#	使用转换说明的可选形式。若为%o格式,则以0开始;若为%x和%Xgeshi ,则以0x或0X开始。对于所有的浮点形式,#保证了即使不跟任何数字,也打印一个小数点字符。对于%g和%G格式,它防止尾随0被删除。示例: “%#o”, “%#8.0f”, “%+#10.3E”
0	对于所有的数字格式,用前导零而不是空格填充字段宽度。如果出现-标志或者指定了精度(对于整数)则忽略该标志。示例: “%010d”, “%08.3f”,"%02X"

常量笔记

FLT_MANT_DIG	float类型的尾数位数
FLT_DIG			float 类型的最少有效数字位数(十进制 )
FLT_MIN_10_EXP  带全部有效教字的 float 类型的最小负指数(以 10 为底)
FLT_MAX_10_EXP  float 类型的最大正指数(以 10 为底)
FLT_MIN			保留全部精度的 float 类型最小正数
FLT_MAX			float 类型的最大正数	
FLT_EPSILON		1.00 和比 1.00 大的最小 float 类型值之间的差值

CHAR BIT	char 类型的位数
CHAR MAX	char 类型的最大值 
CHAR MIN	char 类型的最小值 
SCHAR MAX	signed char 类型的最大值 
SCHAR MIN	signed char 类型的最小值 
UCHAR MAX 	unsigned char 类型的最大值 
SHRT MAX	short 类型的最大值 
SHRT MIN	short 类型的最小值 
USHRT MAX	unsigned short 类型的最大值 
INT MAX		int 类型的最大值 
INT MIN		int 类型的最小值 
UINT MAX 	unsigned int 的最大值 	
LONG MAX	long 类型的最大值 
LONG MIN	long 类型的最小值 
ULONG MAX	unsigned long 类型的最大值 
LLONG MAX	long long 类型的最大值 
LLONG MIN	long long 类型的最小值 
ULLONG MAX	unsigned long long 类型的最大值

ctype.h 头文件中的字符测试函数

isalnum( )	字母数字( 字母或数字 )
isalpha( )	字母
isblank( )	标准的空白字符( 空格、水平制表符或换行符 )或任何其他本地化指定为空白的字符
iscntrl( )	控制字符,如 Ctrl+B
isdigit( )	数字
isgraph( )	除空格之外的任意可打印字符
islower( )	小写字母
isprint( )	可打印字符
ispunct( )	标点符号( 除龙格或字母数字字符以外的任何可打印字符 )
isspace( )	空白字符( 空格、换行符、换页符、回车符、垂直制表符、水平制表符或其他本地化定义的
字符 )
isupper( )	大写字母
isxdigit( )	十六进制数字符

程序清单 1.1 C 源代码示例

#include <stdio.h>

int main(void)
{
	int dogs;
    
	printf("How many dogs do you have?\n");
	scanf_s("%d", &dogs);
	printf("So you have %d dog(s)!\n", dogs);
    
	return 0;
}

1.13 编程练习

你刚被 MacroMuscle 有限公司聘用。该公司准备进入欧洲市场,需要一个把英寸单位转换为厘米单

位(1 英寸=2.54 厘米)的程序。该程序要提示用户输入英寸值。你的任务是定义程序目标和设计

程序(编程过程的第1步和第 2 步)。

#include <stdio.h>

int main(void)
{
	int ch;

	printf("输入英寸值(1英寸=2.54厘米):\n");
	scanf_s("%d", &ch);
    
	return 0;
}

程序清单 2.1 C 源代码示例

#include <stdio.h>

int main(void)	// 一个简单的C程序
{
	int num;	//定义一个名为num的变量
	num = 1;	// 为num赋值

	printf("I am a simple.\n");	//使用printf()函数
	printf("computer.\n");
	printf("My favorite number is %d because it is first.\n", num);

	return 0;
}

程序清单 2.2 C 源代码示例

#include <stdio.h>

int main(void)
{
	int feet, fathoms;

	fathoms = 2;
	feet = 6 * fathoms;

	printf("There are %d feet in %d fathoms!\n", feet, fathoms);
	printf("Yes, I said %d feet!\n", 6 * fathoms);
	return 0;
}

程序清单 2.3 C 源代码示例

#include <stdio.h>

void butler(void);
int main(void)
{
	printf("I will summon the butler function.\n");
	butler();
	printf("Yes. Bring me some tea and writeable DVDs.\n");
	return 0;
}

void butler(void)
{
	printf("You rang,sir?\n");
}

编写一个程序,调用一次 **printf()**函数,把你的姓名打印在一行。再调用一次 **printf()**函数,把你的

姓名分别打印在两行。然后,再调用两次 **printf()**函数,把你的姓名打印在一行。输出应如下所示(当

然要把示例的内容换成你的姓名):

Gustav Mahler 第 1 次打印的内容

Gustav 第 2 次打印的内容

Mahler 第 3 次打印的内容

Gustav Mahler 第 4 次打印的内容

#include <stdio.h>

int main(void)
{
	printf("cyh\n");
	printf("c\n");
	printf("yh\n");
	printf("cyh\n");
	return 0;
}

编写一个程序把你的年龄转换成天数,并显示这两个值。这里不用考虑闰年的问题。

#include <stdio.h>

int main(void)
{
	int age;
	int days = 365;
	printf("请输入你的年龄(1年365天不考虑闰年):\n");
	scanf_s("%d", &age);
	printf("一共有%d天\n", age * days);
	return 0;
}

在 C 语言中,函数可以调用另一个函数。编写一个程序,调用一个名为 one three()的函数。该函数在一行打印单词“ one” ,再调用第 2 个函数 twoO , 然后在另一行打印单词“ three” 。two( )

函数在一行显示单词 “ two” 。main < )函数在调用 one three( )函数前要打印短语 “starting

now:” ,并在调用完毕后显示短语 “ done! ” 。因此,该程序的输出应如下所示:

starting now

one

two

three

done!

#include <stdio.h>

void one_three();
void two();
int main(void)
{
	printf("startingnow:\n");
	one_three();
	two();
	printf("three\n");
	printf("done!");
	return 0;
}

void one_three()
{
	printf("One\n");
}

void two()
{
	printf("two\n");
}

程序清单3.5 C 源代码示例

#include <stdio.h>

int main(void)
{
	char ch;

	printf("Please enter a character.\n");
	scanf_s("%c", &ch);
	printf("The code for %c is %d.\n", ch, ch);
	return 0;
}

程序清单3.6 C 源代码示例

#include <stdio.h>
#include <inttypes.h> //支持可移植类型

int main(void)
{
	int32_t me32; //me32是一个32位有符号整型变量

	me32 = 45933945;
	printf("First, assume int32_t is int:\n");
	printf("me 32=%d\n", me32);
	printf("Next, let's not make any assumptions.\n");
	printf("Instead use a \"macro\"from inttypes.h:");
	printf("me32=%"PRId32"\n", me32);
	return 0;
}

3.11 编程练习

通过试验(即编写带有此类问题的程序)观察系统如何处理整数上溢、浮点数上溢和浮点数下溢的

情况

#include <stdio.h>

int main(void)
{
	int a = 2147483647;
	float b = 3.4E38 * 100.0f;
	float c = (3.4e-38) / (100.0e100);
	printf("%d %d %d\n", a, a + 1, a + 2); //整数上溢
	printf("%e\n", b); //浮点数上溢
	printf("%e\n", c); //浮点数下溢
	return 0;
}

编写一个程序,要求提示输入一个 ASCII 码值(如,66),然后打印输入的字符。

#include <stdio.h>

int main(void)
{
	int ch;
	printf("输入一个ASCLL码值:\n");
	scanf_s("%d", &ch);
	printf("ASCLL码值为:%c", ch);
	return 0;
}

编写一个程序,读取一个浮点数,先打印成小数点形式,再打印成指数形式。然后,如果系统支持,再打印成P 记数法(即十六进制记数法)。按以下格式输出(实际显示的指数位数因系统而异

#include <stdio.h>

int main(void)
{
	float a = 64.25;
	printf("%.2f\n", a);
	printf("%.6f\n", a);
	printf("%e\n", a);
	printf("%a\n", a);
	return 0;
}

一年大约有 3.156X 107秒。编写一个程序,提示用户输入年龄,然后显示该年龄对应的秒数。

#include <stdio.h>

int main(void)
{
	float s = 3.156e7;
	int age;
	printf("输入你的年龄:\n");
	scanf_s("%d", &age);
	printf("一共%f秒", age * s);
	return 0;
}

程序清单4.1 C 源代码示例

#include <stdio.h>
#include <string.h>

#define DENSITY 62.4
int main(void)
{
	float weight, volume;
	int size, letters;
	char name[40] = { 0 };

	printf("Hi! what's your first name?\n");
	scanf_s("%s", name, 40);
	printf("%s,what's your weight in pounds?\n", name);
	scanf_s("%f", &weight);
	size = sizeof(name);
	letters = strlen(name);
	volume = weight / DENSITY;
	printf("Well,%s,your volume is %2.2f cubic feet.\n", name, volume);
	printf("Also,your first name has %d letters.\n", letters);
	printf("and we have %d bytes to store it .\n", size);
	return 0;
}

程序清单4.3 C 源代码示例

#include <stdio.h>
#include <string.h>

#define PRAISE "You are an extraordinary being."
int main(void)
{
	char name[40] = { 0 };

	printf("What's your name?\n");
	scanf_s("%s", name, 40);
	printf("Hello, %s. %s\n", name, PRAISE);
	printf("Your name of %zd letters occupies %zd memory cells.\n", strlen(name), sizeof(PRAISE));
	printf("and occupies %zd memory cells.\n", sizeof(PRAISE));
	return 0;
}

程序清单4.4 C 源代码示例

#include <stdio.h>

#define PI 3.14159
int main(void)
{
	float area, circum, radius;

	printf("What is the radius of your pizza?\n");
	scanf_s("%f", &radius);
	area = PI * radius * radius;
	circum = 2.0 * PI * radius;
	printf("Your basic pizza parameters are as follows:\n");
	printf("circumference = %1.2f, area = %1.2f\n", circum, area);
	return 0;
}

程序清单4.5 C 源代码示例

#include <stdio.h>
#include <limits.h> //整型限制
#include <float.h> //浮点型限制

int main(void)
{
	printf("Some number limits for this system:\n");
	printf("Bigger int:%d\n", INT_MAX);
	printf("Smallest long long: %lld\n", LLONG_MIN);
	printf("One byte = %d bits on this system.\n", CHAR_BIT);
	return 0;
}

程序清单4.6 C 源代码示例

#include <stdio.h>

#define PI 3.141593
int main(void)
{
	int number = 7;
	float pies = 12.75;
	int cost = 7800;

	printf("The %d contestants ate %f berry pies.\n", number, pies);
	printf("The value of pi is %f.\n", PI);
	printf("Farewell thou art too dear for my possessing.\n");
	printf("%c%d\n", '$', 2 * cost);
	return 0;
}

程序清单4.8 C 源代码示例

#include <stdio.h>

int main(void)
{
	const double RENT = 3852.99;

	printf("*%f*\n", RENT);
	printf("*%e*\n", RENT);
	printf("*%4.2f*\n", RENT);
	printf("*%3.1f*\n", RENT);
	printf("*%10.3f*\n", RENT);
	printf("*%+4.2f*\n", RENT);
	printf("*%010.2f*\n", RENT);
	printf("*%+6.2f*\n", RENT);
	return 0;
}

程序清单4.10 C 源代码示例

#include <stdio.h>

#define BLURB "Authentic imitation!"
int main(void)
{
	printf("[%2s]\n", BLURB);
	printf("[%24s]\n", BLURB);
	printf("[%24.5s]\n", BLURB);
	printf("[%-24.5s]\n", BLURB);
	return 0;
}

程序清单4.12 C 源代码示例

#include <stdio.h>
#include <limits.h>

int main(void)
{
	float n1 = 3.0;
	double n2 = 3.0;
	long n3 = 2000000000;
	long n4 = 1234567890;

	printf("%.le %.le %.le %.le\n", n1, n2, (float)n3, (float)n4);
	printf("%ld %ld\n", n3, n4);
	printf("%ld %ld %ld %ld\n", (long)n1, (long)n2, n3, n4);
	printf("%.le %.le %.le %.le\n", n1, n2, n3, n4);
	printf("%ld %ld %ld %ld\n", n1, n2, n3, n4);
	return 0;
}

程序清单4.15 C 源代码示例

#include <stdio.h>

int main(void)
{
	int age;
	float assets;
	char pet[30];

	printf("Enter your age,assets, and favorite pet.\n");
	scanf_s("%d %f", &age, &assets);
	scanf_s("%s", pet, 30);
	printf("%d $%.2f %s\n", age, assets, pet);
	return 0;
}

编写一个程序,提示用户输入名和姓,然后以“名,姓”的格式打印出来。

#include <stdio.h>

int main(void)
{
	char ming[20];
	char xing[20];
	printf("输入姓名:");
	scanf_s("%s", ming, 20);
	scanf_s("%s", xing, 20);
	printf("姓名是:%s,%s.\n", ming, xing);
	return 0;
}

编写一个程序,提示用户输入名和姓,并执行一下操作:

a.打印名和姓,包括双引号;

b. 在宽度为 20 的字段右端打印名和姓,包括双引号;

c. 在宽度为 20 的字段左端打印名和姓,包括双引号;

d. 在比姓名宽度宽 3 的字段中打印名和姓

#include<stdio.h>
#include<string.h>
int main(void)
{
	char name[20];
	printf("请输入你的名字:\n");

	scanf("%s", name);
	printf("\"%s\"\n", name);
	printf("\"%20s\"\n", name);
	printf("\"%-20s\"\n", name);
	printf("\"%*s\"\n", strlen(name) + 3, name);

	return 0;
}

编写一个程序,提示用户输入身高(单位:英寸)和姓名,然后以下面的格式显示用户刚输入的信

息:

Dabney, you are 6.208 feet tall

使用 float 类型,并用/作为除号。如果你愿意,可以要求用户以厘米为单位输入身高,并以米为单

位显示出来。

#include<stdio.h>

int main(void)
{
	float ch_weight; //单位英寸
	char name[40] = { 0 };
	printf("输入身高(单位英寸):");
	scanf_s("%f", &ch_weight);
	printf("输入姓名:");
	scanf_s("%s", name, 40);
	printf("%s, you are %.3f feet tall\n", name, ch_weight);
	float m_weight = ch_weight / 100;
	printf("你的身高:%.3f m", m_weight);
	return 0;
}

编写一个程序,提示用户输入以兆位每秒(Mb/s) 为单位的下载速度和以兆字节(MB) 为单位的

文件大小。程序中应计算文件的下载时间。注意,这里 1 字节等于 8 位。使用 float 类型,并用/作

为除号。该程序要以下面的格式打印 3 个变量的值(下载速度、文件大小和下载时间),显示小数

点后面两位数字:

#include <stdio.h>
#include <float.h>

int main(void)
{
	double b = 1.0 / 3.0;
	float f = 1.0 / 3.0;
	printf("%.6e %.6f\n", b, f);
	printf("%.12e %.12f\n", b, f);
	printf("%.16e %.16f\n", b, f);
	printf("%d %d", FLT_DIG, DBL_DIG);
	return 0;
}

程序清单 5.1 shoes1.c 程序

#include <stdio.h>

#define ADJUST 7.31
int main(void)
{
	const double SCALE = 0.333;
	double shoe, foot;

	shoe = 9.0;
	foot = SCALE * shoe + ADJUST;
	printf("Shoe size (men's) foot length\n");
	printf("%10.1f %15.2f inches\n", shoe, foot);
	return 0;
}

程序清单 5 . 2 shoes2.c 程序

#include <stdio.h>

#define ADJUST 7.31
int main(void)
{
	const double SCALE = 0.333;
	double shoe, foot;

	printf("Shoe size (men's) foot length\n");
	shoe = 3.0;
	while (shoe < 18.5)
	{
		foot = SCALE * shoe + ADJUST;

		printf("%10.1f %15.2f inches\n", shoe, foot);
		shoe += 1.0;
	}
	printf("IF the shoe fits,wear it.\n");

	return 0;
}

程序清单 5.13 addemup.c 程序

#include <stdio.h>

int main(void)
{
	int count, sum;
	count = 0;
	sum = 0;
	while (count++ < 20)
	{
		printf("%d\n", sum);
		sum += count;
		printf("%d\n", sum);
	}
	printf("%d", sum);
	return 0;
}

编写一个程序,把用分钟表示的时间转换成用小时和分钟表示的时间。使用#define 或 const 创

建一个表示 60 的符号常量或 const 变量。通过 while 循环让用户重复输入值,直到用户输入小

于或等于 0 的值才停止循环。

#include <stdio.h>

#define num 60
int main(void)
{
	int number;
	printf("输入一个数字(小时 <=0停止):\n");
	scanf_s("%d", &number);
	while (number > 0)
	{
		printf("你输入的小时数是:%d\n", number);
		printf("转换为分钟数是:%d\n", number * 60);
		scanf_s("%d", &number);
	}
	printf("done!");
	return 0;
}

编写一个程序,提示用户输入 一个整数,然后打印从该数到比该数大 10 的所有整数(例如,用户

输入 5, 则打印 5 15 的所苻整数,包括 5 和 15)。要求打•印的各值之间用一个空格、制表符或换行符分开

#include <stdio.h>

int main(void)
{
	int number;
	int i = 0;
	printf("输入一个整数(打印比该数大10的所有整数):");
	scanf_s("%d", &number);
	while (i <= 10)
	{
		printf("%d\n", number);
		i++;
		number++;
	}
	printf("done!");
	return 0;
}

编写一个程序,提示用户输入天数,然后将其转换成周数和天数。例如,用户输入 18, 则转换成 2

周 4 天。以下面的格式显示结果:

18 days are 2 weeks, 4 days.

通过 while 循环让用户重复输入天数,当用户输入 1个非正值时(如 0 或-20 ), 循环结束。

#include <stdio.h>

int main(void)
{
	int days;
	int weeks = 7;
	printf("输入天数:");
	scanf_s("%d", &days);
	while (days > 0)
	{
		printf("%d days %d weeks %d days.\n", days, days / weeks, days % weeks);
		scanf_s("%d", &days);
	}
	printf("done!");
	return 0;
}

编写一个程序,提示用户输入一个身高(单位:厘米)并分别以厘米和英寸为单位显示该值,允许有小数部分。程序应该能让用户電复输入身高,直到用户输入一个非正值。其输出示例如下:

Enter a height in centimeters: 182

182.0 cm = 5 feet, 11.7 inches

Enter a height in centimeters (<=0 to quit): 168.7

168.0 cm = 5 feet, 6.4 inches

Enter a height in centimeters (<=0 to quit): 0

bye

#include <stdio.h>

#define CMFEET 30.48
#define CMINCHES 2.54
int main(void)
{
	float height; //单位:cm
	int feet;
	float inches;
	printf("输入身高: \n");
	while (scanf_s("%f", &height) > 0)
	{
		feet = height / CMFEET;
		inches = (height - CMFEET * feet) / CMINCHES;
		printf("%d\n", (int)height);
		printf("%.1fcm %dfeet %.1finches", height, (int)feet, inches);
	}
	return 0;
}

修改程序 addemup.c (程序清单 5.13 ), 你可以认为 addemup.c 是计算 20 天里賺多少钱的程序(假设第丨天賺$1 、第 2 天赚$2、第 3 天赚$3, 以此类推)修改程序使其可以与用户交互根据用户输入的数进行计算(即,用读入的一个变量来代替 20

)

#include <stdio.h>

int main(void)
{
	int days;
	int money;
	int i = 1;
	printf("输入盈利了多少天:");
	scanf_s("%d", &days);
	while (i < days)
	{
		money = i;
		printf("第%d天赚$%d\n", i, money);
		i++;
		money++;
	}
	return 0;
}
#include <stdio.h>

int main(void)
{
	int days;
	int money;
	int i = 1;
	printf("输入盈利了多少天:");
	scanf_s("%d", &days);
	while (i < days)
	{
		money = i;
		printf("第%d天赚$%d\n", i, money * money);
		i++;
		money++;
	}
	return 0;
}

编写一个程序,提示用户输入一个 double 类型的数,并打印该数的立方值。自己设汁一个函数计

算并打印立方值。main( )函数要把用户输入的值传递给该函数。

#include <stdio.h>

double function(double b);
int main(void)
{
	double aa;
	printf("输入:");
	scanf_s("%lf", &aa);
	function(aa);
	return 0;
}

double function(double b)
{
	printf("%lf\n", b * b);
}

编写一个程序,显示求模运算的结果。把用户输入的第 1 个整数作为求模运算符的第 2 个运算对象,

该数在运算过程中保持不变。用户后面输入的数是第 1 个运算对象。当用户输入1个非正值时,程序结束。其输出示例如下:

#include <stdio.h>

int main(void)
{
	int a, b = 256;
	printf("%输入一个整数求模运算:");
	scanf_s("%d", &a);
	printf("%d %% %d is %d", a, b, a % b);
	return 0;
}

编写一个程序,要求用户输入一个华氏温度。程序应读取double类型 的值作为温度值,并把该值作为参数传递给一个用户自定义的函数Temperatures()。该函数计算摄氏温度和开氏温度,并以小数点后面两位数字 的精度显示3种温度。要使用不同的温标来表示这3个温度值。下面是华氏温 度转摄氏温度的公式:
摄氏温度 = 5.0 / 9.0 * (华氏温度 - 32.0)
开氏温标常用于科学研究,0表示绝对零,代表最低的温度。下面是摄氏温度转开氏温度的公式: 开氏温度 = 摄氏温度 + 273.16
Temperatures()函数中用const创建温度转换中使用的变量。在main()函数 中使用一个循环让用户重复输入温度,当用户输入 q 或其他非数字时,循环 结束。scanf()函数返回读取数据的数量,所以如果读取数字则返回1,如果读取q则不返回1。可以使用==运算符将scanf()的返回值和1作比较,测试两值是否相等。

#include <stdio.h>

void Temperatures(double n);

int main(void)
{
	double huashiwendu;
	printf("输入华氏温度:");

	while (scanf_s("%lf", &huashiwendu) == 1)
	{
		printf("\n");
		Temperatures(huashiwendu);
		printf("输入字母退出\n");
	}
	printf("done!\n");
	return 0;
}

void Temperatures(double n)
{
	double a = 5.0;
	double b = 9.0;
	double c = 32.0;
	double d = 273.16;
	double sheshiwendu = a / b * (n - c);
	double kaishiwendu = sheshiwendu + d;
	printf("华氏:%.2lf 摄氏:%.2lf 开式:%.2lf", n, sheshiwendu, kaishiwendu);
}

程序清单 6.5 cmpflt.c 程序

#include <stdio.h>
#include <math.h>

int main(void)
{
	const double ANSWER = 3.14159;
	double response;

	printf("What is the value of pi?\n");
	scanf_s("%lf", &response);
	while (fabs(response - ANSWER) > 0.0001)
	{
		printf("Try again\n");
		scanf_s("%lf", &response);
	}
	printf("Close enough!\n");
	return 0;
}

程序清单 6.6 t_and_f.c 程序

#include <stdio.h>

int main(void)
{
	int true_val, false_val;
	true_val = (10 > 2);
	false_val = (10 == 2);
	printf("%d %d", true_val, false_val);
	return 0;
}

程序清单 6.7 truth.c 程序

#include <stdio.h>

int main(void)
{
	int n = 3;
	while (n)
	{
		printf("%2d\n", n--);
	}
	printf("%2d\n", n);
	return 0;
}

程序清单 6.12 for_cube.c 程序

#include <stdio.h>

int main(void)
{
	int num;
	printf("     n   n cubed\n");
	for (num = 1; num <= 6; num++)
	{
		printf("%5d %5d\n", num, num * num);
	}
	return 0;
}

程序清单 6.17 rowsl.c 程序

#include <stdio.h>

#define ROWS 6
#define CHARS 10
int main(void)
{
	int row;
	char ch;

	for (row = 0; row < ROWS; row++)
	{
		for (ch = 'A'; ch < ('A' + CHARS); ch++)
		{
			printf("%c", ch);
		}
		printf("\n");
	}
	return 0;
}

程序清单 6.18 rowsl.c 程序

#include <stdio.h>

#define ROWS 6
#define CHARS 10
int main(void)
{
	int row;
	char ch;

	for (row = 0; row < ROWS; row++)
	{
		for (ch = ('A' + row); ch < ('A' + CHARS); ch++)
		{
			printf("%c", ch);
		}
		printf("\n");
	}
	return 0;
}

程序清单 6.19 scores in.c 程序

#include <stdio.h>

#define SIZE 10
#define PAR 72
int main(void)
{
	int index, score[SIZE];
	int sum = 0;
	float average;

	printf("Enter %d golf scores:\n", SIZE);
	for (index = 0; index < SIZE; index++)
	{
		scanf_s("%d", &score[index]);
		printf("%5d", score[index]);
	}
	printf("\nThe scores read in are as follows:\n");
	//for (index = 0; index < SIZE; index++)
	//{
	//	printf("%5d", score[index]);
	//}
	printf("\n");
	for (index = 0; index < SIZE; index++)
	{
		sum += score[index];
	}
	average = (float)sum / SIZE;
	printf("Sum of scores = %d, average = %.2f\n", sum, average);
	printf("That's a handicap of %.0f.\n", average - PAR);
	return 0;
}

程序清单 6.20 scores in.c 程序

#include <stdio.h>

double power(double n, int p);
int main(void)
{
	double x, xpow;
	int exp;

	printf("Enter a number and the positive integer power\n");
	printf(" to which\n the number will be raised.Enter q\n");
	printf(" to quit.\n");
	while (scanf_s("%lf%d", &x, &exp) == 2)
	{
		xpow = power(x, exp);
		printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
		printf("Enter next pair of numbers or q to quit.\n");
	}
	printf("Hope you enjoyed this power trip -- bye !\n");
	return 0;
}

double power(double n, int p)
{
	double pow = 1;
	int i;

	for (i = 1; i <= p; i++)
	{
		pow *= n;
	}
	return pow;
}

编写一个程序,创建一个包含 26 个元素的数组,并在其中储存 26 个小写字母。然后打印数组的所有内容

#include <stdio.h>

#define SIZE 26
int main(void)
{
	int index;
	char score[SIZE] = { 0 };
	int num = 0;
	for (index = 0; index < SIZE; index++)
	{
		for (score[num] = ('a' + index); score[num] < ('a' + SIZE); score[num]++)
		{
			printf("%c", score[index]);
		}
	}
	return 0;
}

使用嵌套循环按下面的格式打印字符:

#include <stdio.h>

int main(void)
{
	int row, row2, index = 5;
	char a = '$';
	for (row = 0; row < index; row++)
	{
		for (row2 = 0; row2 < row + 1; row2++)
		{
			printf("%c", a);
		}
		printf("\n");
	}
	return 0;
}

使用嵌套循环,按 F面的格式打印字母:

#include <stdio.h>

#define ROWS 6
int main(void)
{
	int row;
	int index = 1;
	char ch;
	for (row = 0; row < ROWS; row++)
	{
		printf("%c", ch = 'F');
		for (ch = ('F' - index); ch >= ('F' - row); ch--)
		{
			printf("%c", ch);
		}
		printf("\n");
	}
	return 0;
}

使用嵌葚循环,按下面的格式打印字母:

#include <stdio.h>

#define ROWS 7
int main(void)
{
	int row;
	int row2;
	char ch = 'A';

	for (row = 1; row < ROWS; row++)
	{
		for (row2 = 0; row2 < row; row2++)
		{
			printf("%c", ch++);
		}
		printf("\n");
	}
	return 0;
}

编写 1个程序,提示用户输入大写字母。使用嵌套循环以下面金字塔型的格式打印字母:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main(void)
{
	char ch;
	int row, r;
	scanf("%c", &ch);
	row = ch - 'A' + 1;

	for (r = 1; r <= row; r++)
	{
		//空格的循环
		int space;
		for (space = row - r + 1; space >= 1; space--)
		{
			printf(" ");
		}

		//正序字母的循环
		int n1;
		char ch1;
		for (ch1 = 'A', n1 = 1; n1 < r; n1++, ch1++)
		{
			printf("%c", ch1);
		}

		//倒序字母的循环
		int n2;
		char ch2;
		for (ch2 = 'A' + r - 1, n2 = row; n2 >= 1 && ch2 >= 'A'; n2--, ch2--)
		{
			printf("%c", ch2);
		}
		printf("\n");
	}

	system("pause");
	return 0;
}

编写一个程序打印一个表格,每一行打印一个整数、该数的平方、该数的立方。要求用户输入表格的上下限。使用一个 for 循环

#include<stdio.h>

int main(void)
{
	int  max, min;
	printf("输入上限:");
	scanf_s("%d", &max);
	printf("输入下限:");
	scanf_s("%d", &min);
	int i;
	for (i = 0; i <= (max - min); i++)
	{
		int n = max - i;
		printf("整数=%d\n平方=%d\n立方=%d\n", n, n * n, n * n * n);
	}
	return 0;
}

编写1个程序把一个单词读入一个字符数组中,然后倒序打印这个单词。提示:strlen( )函数(第 4 章介绍过)可用于计算数组最后一个字符的下标

#include<stdio.h>
#include <string.h>

int main(void)
{
	char ch[50] = { 0 };
	printf("输入一个单词;");
	scanf_s("%s", &ch, 50);
	for (int i = strlen(ch); i >= 0; i--)
	{
		printf("%c", ch[i]);
	}
	return 0;
}

编写一个程序要求用户输入两个浮点数,并打印两数之差除以两数乘积的结果。在用户输入非数字之前程序应循环处理用户输入的每对值

#include<stdio.h>

int main(void)
{
	float a, b;
	printf("输入两个浮点数:\n");
	/*scanf_s("%f %f", &a, &b);*/
	while (scanf_s("%f %f", &a, &b) != 0)
	{
		printf("结果=%.2f\n", (a - b) / (a * b));
		printf("输入两个浮点数:\n");
		scanf_s("%f %f", &a, &b);
		/*if (a < 0 || b < 0)
		{
			printf("done!");
		}*/
	}
	printf("done!");
	return 0;
}

编写一个程序,要求用户输入 -个上限整数和- 个下限整数,汁算从上限到下限范围内所有整数

的平方和,并显示计算结果。然后程序继续提示用户输入上限和下限整数,并显示结果,直到用

户输入的上限整数小于下限整数为止。程序的运行示例如下

#include<stdio.h>

int main(void)
{
	int max, min;
	int sum = 0;
	printf("输入min和max:\n");
	scanf_s("%d %d", &min, &max);
	for (int i = 0; i < max - min; i++)
	{
		for (int j = min + i; j <= max; j++)
		{
			sum += j * j;
		}
		printf("Enter lower and upper integer limits:%d %d\n", min, max);
		printf("The sums of the squares from %d to %d is %d\n", min * min, max * max, sum);
		printf("输入min和max:\n");
		scanf_s("%d %d", &min, &max);
	}
	printf("done!");

	return 0;
}

编写一个程序,在数组中读入8 个整数,然后按倒序打印这 8 个整数。

#include<stdio.h>

int main(void)
{
	int arr[8];
	printf("输入8个整数:\n");

	for (int i = 0; i < 8; i++)
	{
		scanf_s("%d", &arr[i]);
	}
	for (int i = 7; i >= 0; i--)
	{
		printf("%d", arr[i]);
	}
	return 0;
}

编写一个程序,创建一个包含 8 个元素的 int 类型数组,分别把数组元素设置为 2 的前 8 次幂。

使用 for 循环设置数组元素的值,使用 do while 循环显示数组元素的值。

#include<stdio.h>

int main(void)
{
	int i, arr[8];
	int index = 0;
	printf("输入一个数字计算他的前八次幂:");
	scanf_s("%d", &arr[index]);
	for (i = 1; i < 8; i++)
	{
		arr[i] = arr[index] * arr[i - 1];
	}
	i = 0;
	do
	{
		printf("第%d次值为:%d\n", i, arr[i]);
	} while (i++ < 7);
	return 0;
}

6.16编程练习的14-18题未做(pdf的195页)

程序清单 7.1 colddays.c 程序

#include<stdio.h>

int main(void)
{
	const int FREEZING = 0;
	float temperature;
	int cold_days = 0;
	int all_days = 0;

	printf("Enter the list of daily low temperatures.\n");
	printf("Use Celsius, and enter q to quit.\n");
	while (scanf_s("%f", &temperature) == 1)
	{
		all_days++;
		if (temperature < FREEZING)
		{
			cold_days++;
		}
	}
	if (all_days != 0)
	{
		printf("%d days total: %.lf%% were below freezing.\n", all_days, 100.0 * (float)cold_days / all_days);
	}
	else if (all_days == 0)
	{
		printf("No data entered!\n");
	}
	return 0;
}

程序清单 7.2 colddays.c 程序

#include<stdio.h>

#define SPACE ' '
int main(void)
{
	char ch;

	while ((ch = getchar()) != '\n')
	{
		if (ch == SPACE)
		{
			putchar(ch);
		}
		else {
			putchar(ch + 1);
		}
		ch = getchar();
	}
	putchar(ch);
	return 0;
}

程序清单 7.3 colddays.c 程序

#include<stdio.h>
#include<stdbool.h>

int main(void)
{
	unsigned long num;
	unsigned long div;
	bool isPrime;

	printf("Please enter an integer for analysis;");
	printf("Enter q to quit.\n");
	while (scanf_s("%lu", &num) == 1);
	{
		for (div = 2, isPrime = true; (div * div) <= num; div++)
		{
			if (num % div == 0)
			{
				if ((div * div) != num)
					printf("%lu is divisible by %lu and %lu .\n", num, div, num / div);
				else
					printf("%lu is divisible by %lu.\n", num, div);
				isPrime = false;
			}
		}
		if (isPrime)
			printf("%lu is prime.\n", num);
		printf("Please enter an integer for analysis;");
		printf("Enter q to quit.\n");
	}
	printf("bye.\n");
	return 0;
}

程序清单 7.4 colddays.c 程序

#include<stdio.h>

#define PERIOD '.'
int main(void)
{
	char ch;
	int charcount = 0;

	while ((ch = getchar()) != PERIOD)
	{
		if (ch != '"' && ch != '\'')
		{
			charcount++;
		}
	}
	printf("There are %d non-quote characters.\n", charcount);
	return 0;
}

程序清单 7.5 colddays.c 程序

#include<stdio.h>
#include<ctype.h>	//为isspace()函数提供原型
#include<stdbool.h>	//为bool、true、false提供定义

#define STOP '|'
int main(void)
{
	char c;	//读入字符
	char prev;	//读入的前一个字符
	long n_chars = 0L;	//字符数
	int n_lines = 0; //行数
	int n_words = 0; //单词数
	int p_lines = 0; //不完整的行数
	bool inword = false; //如果c在单词中,inword等于true

	printf("Enter text to be analyzed(| to terminate):\n");
	prev = '\n'; //用于识别完整的行
	while ((c = getchar()) != STOP)
	{
		n_chars++;	// 统计字符
		if (c == '\n')
		{
			n_lines++;	//统计行
		}
		if (!isspace(c) && !inword)
		{
			inword = true;	//开始一个新的单词
			n_words++;	//统计单词
		}
		if (isspace(c) && inword)
		{
			inword = false;
		}
		prev = c;
	}
	if (prev != '\n')
	{
		p_lines = 1;
	}
	printf("characters = %ld, words = %d, lines = %d", n_chars, n_words, n_lines);
	printf(",partial lines = %d\n", p_lines);
	return 0;
}

程序清单 7.6 colddays.c 程序

#include<stdio.h>

#define COVERAGE 350
int main(void)
{
	int  sq_feet;
	int cans;

	printf("Enter number of square feet to be painted:\n");
	while (scanf_s("%d", &sq_feet) == 1)
	{
		cans = sq_feet / COVERAGE;
		cans += ((sq_feet % COVERAGE == 0)) ? 0 : 1;
		printf("You need %d %s of paint.\n", cans, cans == 1 ? "can" : "cans");
		printf("Enter next value (q to quit):\n");
	}
	return 0;
}

程序清单 7.9 colddays.c 程序

#include<stdio.h>

int main(void)
{
	const float MIN = 0.0f;
	const float MAX = 100.0f;
	float score;
	float total = 0.0f;
	int n = 0;
	float min = MAX;
	float max = MIN;

	printf("Enter the first score (q to quit):");
	while (scanf_s("%f", &score) == 1)
	{
		if (score<MIN || score>MAX)
		{
			printf("%.1f is an invalid value. Try again:", score);
			continue;
		}
		printf("Accepting %.1f:\n", score);
		min = (score < min) ? score : min;
		max = (score > max) ? score : max;
		total += score;
		n++;
		printf("Enter next score (q to quit):");
	}
	if (n > 0)
	{
		printf("Average of %d scores is %.1f .\n", n, total / n);
		printf("Low = %.1f, high = %.1f\n", min, max);
	}
	else
	{
		printf("No valid scores were entered.\n");
	}
	return 0;
}

程序清单 7.10 break,c 程序

#include<stdio.h>

int main(void)
{
	float length, width;

	printf("Enter the length of the rectangle:\n");
	while (scanf_s("%f", &length) == 1)
	{
		printf("Length = %.2f:\n", length);
		printf("Enter its width:\n");
		if ((scanf_s("%f", &width)) != 1)
		{
			break;
		}

		printf("Width = %.2f:\n", width);
		printf("Area = %.2f:\n", length * width);
		printf("Enter the length of the rectangle:\n");
	}
	printf("done.\n");
	return 0;
}

程序清单 7.11 break,c 程序

#include<stdio.h>
#include<ctype.h>

int main(void)
{
	char ch;

	printf("Give me a letter of the alphabet, and I will give");
	printf("an animal name\n beginning with that letter.\n");
	printf("Please type in a letter; type # to end my act.\n");
	while ((ch = getchar()) != '#')
	{
		if ('\n' == ch)
		{
			continue;
		}
		if (islower(ch))
		{
			switch (ch)
			{
			case 'a':
				printf("aragli, a wild sheep of Asia\n");
				break;
			case 'b':
				printf("babirusa, a wild pig of Malay\n");
				break;
			case 'c':
				printf("coati, racoonlike mammal\n");
				break;
			case 'd':
				printf("desman, aquatic, molelike critter\n");
				break;
			case 'e':
				printf("echidna, the spiny anteater\n");
				break;
			case 'f':
				printf("fisher, brownish marten\n");
				break;
			default:
				printf("That's a stumper!\n");
			}
		}
		else
		{
			printf("I recognize only lowercase letters.\n");
		}
		while (getchar() != '\n')
		{
			continue;
		}
		printf("Please type another letter or a #.\n");
	}
	printf("bye!\n");
	return 0;
}

程序清单 7.12 break,c 程序

#include<stdio.h>

int main(void)
{
	char ch;
	int a_ct, e_ct, i_ct, o_ct, u_ct;

	a_ct = e_ct = i_ct = o_ct = u_ct = 0;
	printf("Enter some text; enter # to quit.\n");
	while ((ch = getchar()) != '#')
	{
		switch (ch)
		{
		case 'a':
		case 'A':
			a_ct++;
			break;
		case 'e':
		case 'E':
			e_ct++;
			break;
		case 'i':
		case 'I':
			i_ct++;
			break;
		case 'o':
		case 'O':
			o_ct++;
			break;
		case 'u':
		case 'U':
			u_ct++;
			break;
		default:
			break;
		}
	}
	printf("number of vowels: A E I O U \n");
	printf("     %4d %4d %4d %4d %4d\n", a_ct, e_ct, i_ct, o_ct, u_ct);
	return 0;
}

编写一个程序读取输入,读到#字符停止,然后报告读取的空格数、换行符数和所有其他字符的

数量。

#include<stdio.h>

int main(void)
{
	char ch;
	int kg = 0;
	int hh = 0;
	int qt = 0;
	printf("读取输入:\n");
	while ((ch = getchar()) != '#')
	{
		if (ch == ' ')
		{
			kg++;
			continue;
		}
		else if (ch == '\n')
		{
			hh++;
			continue;
		}
		else
		{
			qt++;
		}
	}
	printf("空格=%d 换行=%d 其他=%d ", kg, hh, qt);
	return 0;
}

编写一个程序读取输入,读到#字符停止。程序要打印每个输入的字符以及对应的 ASCII 码(十进制)。1行打印 8个字符。建议:使用字符计数和求模运算符(%) 在每 8 个循环周期时打印一个换行符。

#include <stdio.h>

int main(void)
{
	int i = 0;
	char ch = 0;
	printf("please enter text to be analyzed:(# to terminate):\n ");
	while ((ch = getchar()) != '#')
	{
		if ((i % 8 == 0) && i != 0)
		{
			printf(" ");
		}
		i++;
		printf("%c %d  ", ch, ch);
	}

	return 0;
}

编写一个程序,读取整数直到用户输入 0。输入结束后,程序应报告用户输入的偶数(不包括 0)

个数、这些偶数的平均值、输入的奇数个数及其奇数的平均值

#include <stdio.h>

int main(void)
{
	int number;
	int oushu_number = 0, oushu_zonghe = 0;
	int jishu_number = 0, jishu_zonghe = 0;
	printf("输入整数,以0结束:\n");
	while (scanf_s("%d", &number) != 0 && (number > 0))
	{
		if (number == 0)
		{
			break;
		}
		if (number % 2 == 1)
		{
			jishu_number++;
			jishu_zonghe += number;
		}
		else
		{
			oushu_number++;
			oushu_zonghe += number;
		}
	}
	printf("偶数个数=%d 偶数平均值=%d 奇数个数=%d 奇数平均值=%d", oushu_number, oushu_zonghe / oushu_number, jishu_number, jishu_zonghe / jishu_number);
	return 0;
}

编写程序读取输入,读到#停止,报告 ei 出现的次数

该程序要记录前一个字符和当前字符.用 “Receive your eieio award” 这样的输入来测试

#include <stdio.h>

int main(void)
{
	char ch;
	char a = 'e';
	char b = 'i';
	int n = 0;
	printf("输入一句字母:\n");
	scanf_s("%c", &ch, 100);
	while (ch != '#')
	{
		if (ch == '#')
		{
			break;
		}
		if (ch == a)
		{
			ch = getchar();
			if (ch == b)
			{
				n++;
			}
		}
		else
		{
			ch = getchar();
		}
	}
	printf("%d", n);
	return 0;
}

编写一个程序,提示用户输入一周工作的小时数,然后打印工资总额、税金和净收入。做如下假设

a. 基本工资 = 1000 美元/小时

b. 加班(超过 40 小时) = 1.5 倍的时间

c. 税率: 前 3 0 0 美元为 1 5%

续 1 5 0 美元为 2 0%

余下的为 25%

#include <stdio.h>

int main(void)
{
	int h_meiyuan = 1000; //1小时1000美元
	int jiaban_40h = 1.5;
	double shuilv_300 = 300 * 0.15;
	double shuilv_150 = 150 * 0.20;
	double shuilv_yuxia = 0.25;
	double shuilv = 0;
	double shuilv_zongshouru = 0;
	double shuilv_jingshouru = 0;
	int time_40_yishang = 0;
	int time = 0;
	printf("输入一周工作了多少小时:\n");

	while ((scanf_s("%d", &time)) != 0 && (time > 0))
	{
		if (time <= 40)
		{
			shuilv_zongshouru = time * h_meiyuan;
			shuilv_jingshouru = (time * h_meiyuan) - (shuilv_300 + shuilv_150 + ((time * h_meiyuan - 300 - 150) * shuilv_yuxia));
			shuilv = shuilv_300 + shuilv_150 + ((time * h_meiyuan - 300 - 150) * shuilv_yuxia);
		}
		if (time > 40)
		{
			time_40_yishang = ((time - 40) * jiaban_40h) + 40;
			shuilv_zongshouru = time_40_yishang * h_meiyuan;
			shuilv_jingshouru = (time_40_yishang * h_meiyuan) - (shuilv_300 + shuilv_150 + ((time_40_yishang * h_meiyuan - 300 - 150) * shuilv_yuxia));
			shuilv = shuilv_300 + shuilv_150 + ((time_40_yishang * h_meiyuan - 300 - 150) * shuilv_yuxia);
		}
	}

	printf("总收入=%.2f 税率=%.2f 净收入=%.2f", shuilv_zongshouru, shuilv, shuilv_jingshouru);
	return 0;
}

7.12编程练习8、10-11不会做

程序清单 8.1 echo.c 程序

#include <stdio.h>

int main(void)
{
	char ch;
	while ((ch = getchar()) != '#')
	{
		putchar(ch);
	}
	return 0;
}

程序清单 8.4 guess.C 程序

#include <stdio.h>
int main(void)
{
	int guess = 1;

	printf("Pick an integer from 1 to 100. I will try to guess\n");
	printf("it.\n Respond with a y if my guess is right and with\n");
	printf("\n an n if is wrong.\n");
	printf("Uh...is your number %d?\n", guess);
	while (getchar() != 'y')
	{
		printf("Well,then,is it %d?\n", ++guess);
	}
	printf("I knew I could do it!\n");

	system("pause");
	return 0;
}

优化后

#include <stdio.h>
int main(void)
{
	int guess = 1;
	char response;

	printf("Pick an integer from 1 to 100. I will try to guess");
	printf("it.\n Respond with a y if my guess is right and with");
	printf("\n an n if it is wrong.\n");
	printf("Uh...is your number %d?\n", guess);
	while ((response = getchar()) != 'y') //获取响应
	{
		if (response == 'n')
		{
			printf("Well then is it%d?\n", ++guess);
		}
		else
		{
			printf("Sorry, I understand only y or n.\n");
		}
		while (getchar() != '\n')
		{
			continue; // 跳过剩余的输入行
		}
	}
	printf("I knew I could do it!\n");

	system("pause");
	return 0;
}

程序清单 8.5 showcharl.c 程序

#include <stdio.h>

void display(char cr, int lines, int width);
int main(void)
{
	int ch;//待打印字符
	int rows, cols; //行数和列数
	printf("Enter a character and two integers:\n");
	while ((ch = getchar()) != '\n')
	{
		scanf_s("%d %d", &rows, &cols);
		display(ch, rows, cols);
		printf("Enter another character and two integers;\n");
		printf("Enter a newline to quit.\n");
	}
	printf("bye,\n");

	system("pause");
	return 0;
}

void display(char cr, int lines, int width)
{
	int row, col;
	for (row = 1; row <= lines; row++)
	{
		for (col = 1; col <= width; col++)
		{
			putchar(cr);
		}
		putchar('\n');//结束一行并开始新的一行
	}
}

程序清单 8.6 showchar2.c 程序

#include <stdio.h>
void display(char cr, int lines, int width);
int main(void)
{
	int ch;//待打印字符
	int rows, cols; //行数和列数
	printf("Enter a character and two integers:\n");
	while ((ch = getchar()) != '\n')
	{
		if (scanf_s("%d %d", &rows, &cols) != 2)
			break;
		display(ch, rows, cols);
		while (getchar() != '\n')
			continue;
		printf("Enter another character and two integers;\n");
		printf("Enter a newline to quit.\n");
	}
	printf("bye,\n");
	return 0;
}

void display(char cr, int lines, int width)
{
	int row, col;
	for (row = 1; row <= lines; row++)
	{
		for (col = 1; col <= width; col++)
			putchar(cr);
		putchar('\n');//结束一行并开始新的一行
	}
}

程序清单 8.7 checking.c 程序

#include <stdio.h>
#include <stdbool.h>

// 验证输入是一个整数
long get_long(void);
// 验证范围的上下限是否有效
bool bad_limits(long begin, long end, long low, long high);
// 计算a~b之间的整数平方和
double sum_squares(long a, long b);
int main(void)
{
	const long MIN = -10000000L;//范围上限
	const long MAX = +10000000L;//范围下限
	long start;//用户指定的范围最小值
	long stop;//用户指定的范围最大值
	double answer;

	printf("This program computes the sum of the squares of"
		"integer is a range.\nThe lower bound should not"
		"be less than -10000000 and\nthe upper bound"
		"should not be more than +10000000.\nEnter the"
		"limits (enter 0 for both limits to quit):\n"
		"lower limit:");
	start = get_long();
	printf("upper limit:");
	stop = get_long();
	while (start != 0 || stop != 0)
	{
		if (bad_limits(start, stop, MIN, MAX))
		{
			printf("Please try again.\n");
		}
		else
		{
			answer = sum_squares(start, stop);
			printf("The of the squares of the integers");
			printf("from %ld to %ld is %g\n", start, stop, answer);
		}
		printf("Enter the limits (enter 0 for both"
			"limits to quit):\n");
		printf("lower limit:");
		start = get_long();
		printf("upper limit:");
		stop = get_long();
	}
	printf("done.\n");
	return 0;
}

long get_long(void)
{
	long input;
	char ch;
	while ((scanf_s("%ld", &input)) != 1)
	{
		while ((ch = getchar()) != '\n')
		{
			putchar(ch);
		}

		printf("is not an integer.\nPlease enter an");
		printf("integer value, such as 25, -178, or 3:");
	}

	return input;
}

double sum_squares(long a, long b)
{
	double total = 0;
	long i;
	for (i = a; i <= b; i++)
	{
		total += (double)i * (double)i;
	}

	return total;
}

bool bad_limits(long begin, long end, long low, long high)
{
	bool not_good = false;

	if (begin > end)
	{
		printf("%ld isn11 smaller than %ld.\n", begin, end);
		not_good = true;
	}
	if (begin < low || end < low)
	{
		printf("Values must be %ld or greater.\n", low);
		not_good = true;
	}
	if (begin > high || end > high)
	{
		printf("Values must be %ld or less.\n", high);
		not_good = true;
	}

	return not_good;
}

程序清单 9.1 letheadl.c 程序(书上的报错下标越界,目前没找到原因)

#include <stdio.h>

#define NAME "GIGATHINK, INC."
#define ADDRESS "101 Megabuck Plaza"
#define PLACE "Megapolis, CA 94904"
#define WIDTH 40

void starbar(void);
int main(void)
{
	starbar();
	printf("\n");
	printf("%s\n", NAME);
	printf("%s\n", ADDRESS);
	printf("%s\n", PLACE);
	starbar(); //使用函数
	return 0;
}

void starbar(void)
{
	int count;
	for (count = 1; count <= WIDTH; count++)
	{
		printf("*");
	}
}

程序清单 9.2 lethead2 .c 程序

#include <stdio.h>
#include <string.h>

#define NAME "GIGATHINK, INC."
#define ADDRESS "101 Megabuck Plaza"
#define PLACE "Megapolis, CA 94904"
#define WIDTH 40
#define SPACE ' '

void show_n_char(char ch, int num);
int main(void)
{
	int spaces;

	show_n_char('*', WIDTH);
	putchar('\n');
	show_n_char(SPACE, 12);
	printf("%s\n", NAME);
	spaces = (WIDTH - strlen(ADDRESS)) / 2;
	show_n_char(SPACE, spaces);
	printf("%s\n", ADDRESS);
	show_n_char(SPACE, (WIDTH - strlen(PLACE)) / 2);
	printf("%s\n", PLACE);
	show_n_char('*', WIDTH);
	putchar('\n');
	return 0;
}

void show_n_char(char ch, int num)
{
	int count;
	for (count = 1; count <= num; count++)
	{
		putchar(ch);
	}
}

程序清单 9.3 lesser.c 程序

#include <stdio.h>

int imin(int, int);
int main(void)
{
	int evi11, evi12;

	printf("Enter a pair of integers (q to quit):\n");

	while (scanf_s("%d %d", &evi11, &evi12) == 2)
	{
		printf("The lesser of %d and %d is %d \n", evi11, evi12, imin(evi11, evi12));
		printf("Enter a pair of integers (q to quit):\n");
	}
	printf("Bye.\n");

	return 0;
}

int imin(int n, int m)
{
	int min;

	if (n < m)
	{
		min = n;
	}
	else {
		min = m;
	}

	return min;
}

优化

#include <stdio.h>

int imin(int, int);
int main(void)
{
	int evi11, evi12;

	printf("Enter a pair of integers (q to quit):\n");

	while (scanf_s("%d %d", &evi11, &evi12) == 2)
	{
		printf("The lesser of %d and %d is %d \n", evi11, evi12, imin(evi11, evi12));
		printf("Enter a pair of integers (q to quit):\n");
	}
	printf("Bye.\n");

	return 0;
}

int imin(int n, int m)
{
	return (n < m) ? n : m;
}

程序清单 9.5 proto.c 程序

#include <stdio.h>

int imax(int, int);
int main(void)
{
	printf("The maximum of %d and %d is %d.\n", 3, 5, imax(3.9, 5.4));
	printf("The maximum of %d and %d is %d.\n", 3, 5, imax(3.0, 5.0));
	return 0;
}

int imax(int n, int  m)
{
	return (n > m ? n : m);
}

程序清单 9.6 recur.c 程序

#include <stdio.h>

void up_and_down(int);
int main(void)
{
	up_and_down(1);
	return 0;
}

void up_and_down(int n)
{
	printf("Level %d:n location %p \n", n, &n);
	if (n < 4)
	{
		up_and_down(n + 1);
	}

	printf("LEVEL %d:n location %p \n", n, &n);
}

程序清单 9.7 factor.c 程序

#include <stdio.h>

long fact(int n);
long rfact(int n);
int main(void)
{
	int num;

	printf("This program calculates factorials.\n");
	printf("Enter a value in the range 0-12 (q to quit):\n");

	while (scanf_s("%d", &num) == 1)
	{
		if (num < 0)
		{
			printf("No negative numbers, please.\n");
		}
		else if (num > 12)
		{
			printf("Keep input under 13.\n");
		}
		else
		{
			printf("loop: %d factorial = %ld\n", num, fact(num));
			printf("recursion: %d factorial = %ld\n", num, rfact(num));
		}
		printf("Enter a value in the range 0-12 (q to quit):\n");
	}
	printf("bye.\n");
	return 0;
}

long fact(int n)//使用循环的函数
{
	long ans;

	for (ans = 1; n > 1; n--)
	{
		ans *= n;
	}
	return ans;
}

long rfact(int n)//使用递归的函数

{
	long ans;

	if (n > 0)
	{
		ans = n * rfact(n - 1);
	}
	else
	{
		ans = 1;
	}
	return ans;
}

程序清单 9.8 binary.c 程序

#include <stdio.h>

void to_binary(unsigned long n);
int main(void)
{
	unsigned long number;
	printf("Enter an integer(q to quit):\n");
	while (scanf_s("%lx", &number) == 1)
	{
		printf("Binary equivalent:");
		to_binary(number);
		putchar('\n');
		printf("Enter an integer(q to quit):\n");
	}
	printf("Done.\n");
	return 0;
}

void to_binary(unsigned long n)
{
	int r;

	r = n % 2;
	if (n >= 2)
	{
		to_binary(n / 2);
	}
	putchar(r == 0 ? '0' : '1');
}

使用头文件,下面三个程序

usehotel.cpp

#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.cpp

#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 OlympicXn\n");
	printf("3) Chertworthy Plaza  4) The Stockton\n");
	printf("5) quit\n");
	printf("%s%s\n", STARS, STARS);
	while ((status = scanf_s("%d", &code)) != 1 || (code < 1 || code>5))
	{
		if (status != 1)
		{
			scanf_s("%*s");
		}
		printf("Enter an integer from 1 to 5,please.\n");
	}
	return code;
}

int getnights(void)
{
	int nights;

	printf("How many nights are needed?\n");
	while (scanf_s("%d", &nights) != 1)
	{
		scanf_s("%*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 $%.2f.\n", total);
}

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 STARS "********************"

// 显示选择列表
int menu(void);

// 返回预订天数
int getnights(void);

//根据费率、入住天数计算费用并显示结果
void showprice(double rate, int nights);
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值