C Primer Plus 第六版 第八章 编程练习参考答案

1、设计一个程序,统计在读到文件结尾之前读取的字符数。

#include <stdio.h>

int main(void)
{
	char ch =  0;
	int n_ch = 0;
	while ((ch = getchar()) != EOF)
	{
		n_ch++;
	}
	printf("There are %d characters in the file!\n",n_ch);    //按回车+ctrl+z+回车文件结尾


	return 0;
}

2、编写一个程序,在遇到EOF之前,把输入作为字符流读取。程序要打印每个输入的字符及其相应的ASCII十进制值。注意,在ASCII序列中,空格字符前面的字符都是非打印字符,要特殊处理这些字符。如果非打印字符是换行符或制表符,则分别打印\n或\t。否则,使用控制字符表示法。例如,ASCII的1是Ctrl+A, 可显示为^A。注意,A的ASCII值是CtrI+A的值加上64.其他非打印字符也有类似的关系。除每次遇到换行符打印新的一行之外, 每行打印10对值。(注意,不同的操作系统其控制字符可能不同。)

#include <stdio.h>

int main(void)
{
	char ch = 0;
	int n_ch = 0;
	while ((ch = getchar()) != EOF)
	{
		n_ch++;
		
		if (ch < ' ')
		{
			if ('t' == ch)
			{
				printf("   ");
				putchar('\\');
				putchar('t');
				printf(":%d", ch);
			}
			else if ('\n ' == ch)
			{
				
				printf("   ");
				putchar('\\');
				putchar('n');
				putchar(":%d", ch);
		
			}
			else
			{
				
				printf("   ");
				putchar('^');
				putchar(ch+64);
				printf(":%d", ch);
			}
		}
		else
		{
			printf("   ");
			putchar(ch);
			printf(":%d", ch);
		}
		if (n_ch % 10 == 0)
		{
			printf("\n");
		}
	}
	return 0;
}

3、编写一个程序, 在遇到EOF之前,把输入作为字符流读取。该程序要报告输入中的大写字母和小写字母的个数。假设大小写字母数值是连续的。或者使用ctype .h库中合适的分类函数更方便。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
        char ch = 0;
        int n_upper = 0;
        int n_lower = 0;

        while ((ch = getchar()) !='&')
        {
            if (islower(ch))
            {
                n_lower++;
            }
            else if (isupper(ch))
            {
                n_upper++;
            }
        }

        printf("There are %d upper character and %d lower charecter.\n", n_upper, n_lower);

        return 0;

}

4. 编写一个程序,在遇到EOF之前,把输入作为字符流读取。该程序要报告平均每个单词的字母数, 不要把空白统计为单词的字母。实际上,标点符号也不应该统计,但是现在暂时不同考虑这么多(如果你比较在意这点,考虑使用ctype.h系列中的ispunct ()函数)。

#include <stdio.h>
#include <ctype.h>  //参考书P195程序清单7.7//参考别人

int main(void)
{
    char ch = 0;
    char ch_pre = 0;
    int n_word = 0;
    int n_ch = 0;
    int total_ch = 0;
    int word_ch = 0;
    double word_ch_avg = 0;

    while (ch = getchar())        //从第一个字母开始
    {
        if (isalpha(ch))
        {
            break;
        }
    }

    while (ch != '&')
    {
      if((' ' == ch || '\n' == ch) && !isspace(ch_pre) && !ispunct(ch_pre))
      {
      n_word++;
      total_ch += word_ch;
      word_ch = 0;
       }

       else if (isspace(ch))
        {
        ch_pre = ch;
        ch = getchar();
        continue;
         }

       if (!ispunct(ch) && !isspace(ch))
         {
             word_ch++;
         }
         ch_pre = ch;
         ch = getchar();
    }

       if (!isspace(ch_pre))
    {
        n_word++;
        total_ch += word_ch;
    }

    word_ch_avg = (double)total_ch / n_word;

    printf("Total words: %d, Total characters: %d, Characters per word: %.2lf", n_word, total_ch, word_ch_avg);
    return 0;
}

5. 修改程序清单8.4的猜数字程序,使用更智能的猜测策略。例如,程序最初猜50,询问用户是猜大了、猜小了还是猜对了。如果猜小了,那么下一次猜测的值应是50和100中值,也就是75。 如果这次猜大了,那么下一次猜测的值应是50和75的中值,等等。使用二分查找(binary search)策略,如果用户没有欺骗程序,那么程序很快就会猜到正确的答案。

#include <stdio.h>
#include <stdlib.h>
//笔记:scanf("%c",&ch)与scanf(" %c",&ch)。 书P95
int main()
{
    float min;
    float max;
	float guess;
    char ch = 0;
    char ch_1 = 0;
	printf("please input guess interval:\n");
	scanf_s("%f %f",&min,&max);
	//scanf_s("%d", max);
	if(max >= min)
	{
		printf("i'll guess the number between %.1f and %.1f\n", min,max);
	}
	guess = (max + min) / 2;
	printf("i guest the number is %.1f. is it right(y/n)?\n",guess);
    scanf_s(" %c", &ch);
    getchar();
    while ('y' != ch)
    {
        printf("ok, the number you chosen is bigger or smaller than i guess?(b/s)\n");
        scanf_s(" %c", &ch_1);
        //getchar();
       // putchar(ch_1);
        if ('b' == ch_1)
        {
            min = guess;
            //printf("123\n");
            guess = (min + max) / 2;
        }
        else 
        {
            max = guess;
            //printf("456\n");
            guess = (min + max) / 2;
        }

        printf("i guess the number is %.1f, is it right(y/n)?\n", guess);
        scanf_s(" %c", &ch);
       // getchar();
    }

    printf("yeah, i got it!");
	return 0;
}

6、 修改程序清单8.8中的get_ first()函数, 让该函数返回读取的第1个非空白字符,并在一个简单的程序中测试。

#include <stdio.h>
#include <ctype.h>
char get_first(void)
{
    int ch = 0;

    while (!isalpha(ch = getchar()))
    {
        continue;
    }

    return ch;
}
int main(void)
{
    char ch = get_first();
    putchar(ch);
	return 0;
}

7、 修改第7章的编程练习8,用字符代替数字标记菜单的选项。用q代替5作为结束输入的标记。

#include <stdio.h>
#include <stdio.h>
#define rate1  0.15         //写成百分数报错
#define rate2 0.2
#define rate3  0.25
int main(void)
{
	double hour = 0;
	double sum_wage = 0;
	double rate = 0;
	double income = 0;
	double hour_wage = 0;
	char choice ;

	while(1)
	{
		printf("Enter the number corresponding to the desered pay rate or action:\n");
		printf("a) $8.75/hr         b)9.33/hr\n3)$10.00/hr         c)$11.20/hr\nd)quit\n");
		scanf_s("%c", &choice);

		switch (choice)
		{
		case 'a': hour_wage = 8.75;
			break;
		case 'b': hour_wage = 9.33;
			break;
		case 'c': hour_wage = 10.00;
			break;
		case 'd': hour_wage = 11.20;
			break;
		case 'q':return;                    //输入q,结束
		default:
			printf("Please enter the choice from a to d and q:\n");
			continue;
		}
		printf("Please enter the hours of work per week:\n");
		scanf_s("%lf", &hour);
	   if (hour <= 40)
		{
		sum_wage = 10.00 * hour;
		}
		else
		sum_wage = 10.00 * hour + (hour - 40) * 1.5 * 10.00;
		if (sum_wage <= 300)
		{
			rate = (rate1)*sum_wage;
		}
		else if ((sum_wage >= 300) && (sum_wage <= 450))
		{
			rate = (rate1) * 300 + (rate2) * (sum_wage - 300);
		}
		else
		{
			rate = (rate1) * 300 + (rate2) * 150 + (rate3) * (sum_wage - 450);
		}
		income = sum_wage - rate;
		printf("wage:$%lf.rate:$%lf.income:$%lf.\n", sum_wage, rate, income);
	}


	return 0;
}

8、编写一个程序,显示一个提供加法、减法、乘法、除法的菜单。获得用户选择的选项后,程序提示用户输入两个数字,然后执行用户刚才选择的操作。该程序只接受菜单提供的选项。程序使用float类型的变量储存用户输入的数字,如果用户输入失败,则允许再次输入。进行除法运算时,如果用户输入0作为第2个数(除数),程序应提示用户重新输入一个新值。该程序的一个运行示例如下:

Enter the operation of your choice:

a. add         s. subtract

m. multiply     d. divide

q. quit

Enter first number: 22 . 4

Enter second number:one

one is not an number.

Please enter a number, such as 2.5,-1.78E8, or 3: 1

22.4+1=23.4

Enter the operation of your choice:

a. add          s. subtract

m. multiply      d. divide

q. quit

d

Enter first number: 18.4

Enter second number: 0

Enter a number other than 0: 0.2

18.4 / 0.2= 92

Enter the operation of your choice:

a. add          s. subtract

m. multiply      d. divide

q. quit

Bye.

#include<stdio.h>
#define ABS_VAL 0.000001 //浮点数不是一个精确数值,无法判断是否等于0,,设置一个判断阈值
int main()
{
	char choice;
	float num1, num2;
	while (1)
	{
		printf("Enter the operation of your choice:\n");
		printf("%-20s%-20s\n%-20s%-20s\n%-20s\n", "a.add", "s.subtract", "m.multiply", "d.divide", "q.quit");
		if ((scanf_s("%c", &choice) != 1) || (choice != 'q') && (choice != 'a') && (choice != 's') && (choice != 'm') && (choice != 'd'))
		{
			printf("Please enter the correct operation, please enter again!\n");
			while (getchar() != '\n')
			{
				continue;
			}
			continue;
		}
		if (choice == 'q')
			break;
		//输入第一个数字
		printf("Enter first number:");
		while (scanf_s("%f", &num1) != 1)
		{
			char ch = 0;
			while ((ch = getchar()) != '\n')
			{
				putchar(ch);
			}
			printf(" is not an number.\n");
			printf("Please enter a number, such as 2.5, -1.78E8, or 3: \n");
		}


		//输入第二个数字
		printf("Enter second number:");
		while (scanf_s("%f", &num2) != 1)
		{
			char ch = 0;
			while ((ch = getchar()) != '\n')
			{
				putchar(ch);
			}
			printf(" is not an number.\n");
			printf("Please enter a number, such as 2.5, -1.78E8, or 3: \n");
		}

		switch (choice)
		{
			//加
		case 'a':
			printf("%.1f + %.1f = %.1f\n\n", num1, num2, num1 + num2);
			break;
			//减
		case 's':
			printf("%.1f - %.1f = %.1f\n\n", num1, num2, num1 - num2);
			break;
			//乘
		case 'm':
			printf("%.1f * %.1f = %.1f\n\n", num1, num2, num1 * num2);
			break;
		case 'd':
			while (num2 > -ABS_VAL && num2 < ABS_VAL)
			{
				printf("Enter a number other than 0:");
				while (scanf_s("%f", &num2) != 1)
				{
					char ch = 0;
					while ((ch = getchar()) != '\n')
					{
						putchar(ch);
					}
					printf(" is not an number.\n");
					printf("Please enter a number, such as 2.5, -1.78E8, or 3: ");
				}
				getchar();
			}
			printf("%f / %f = %f\n", num1, num2, (num1 / num2));
			break;

		}
		
	}
	return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值