C Primer Plus 第六版编程练习第七章答案

1,编写一个程序读取输入,读到#字符停止,然后报告读取空格数,换行符数目以及所有的其它字符数目。

/*7.12*/
#include<stdio.h>
#define STOP '#'
#define BLACK ' '
#define NEWLINE '\n'
int main()
{
	char ch;
	int n_black = 0;
	int n_NEWLINE = 0;
	int n_others = 0;
	printf("please enter the char:");
	while ((ch = getchar()) != STOP)
	{
		printf("%c", ch);         //**一个一个字符打印
		if (ch == BLACK)
		{
			n_black++;
		}
		else if (ch == NEWLINE)
		{
			n_NEWLINE++;
		}
		else
			n_others++;
		
	}
	printf("%d%d%d", n_black, n_NEWLINE, n_others);
	return 0;
}

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

/*2*/
#include<stdio.h>
#define STOP '#'
int main()
{
	char ch;
	int i = 0;
	printf("please enter:\n");
	while ((ch = getchar()) != STOP)
	{
		i++;
	 printf("%c,%d\t", ch, ch);
	 if (i % 8 == 0)
		 printf("\n");
	}
}

3.编写一个程序,读取整数,直到用户输入0。输入结束后,程序应该报告输入的偶数(不包括0)个数、这些偶数的平均值,输入的奇数个数以及奇数的平均值。

/*3*/
#include<stdio.h>
int main()
{
	int int_num;
	int opp_num = 0, pair_num = 0;
	float average_opp, average_pair;
	int opp_sum = 0, pair_sum = 0;
	printf("please enter a int num(0 to stop)\n");
	while ((scanf_s("%d", &int_num) == 1) && int_num !=0)
	{
		if (int_num % 2 == 1)                     
	//如何求平均数呢? 要搞清楚while的原理,虽然一开始我输入了很多数,但while本来就是一个数一个数的进行检验的。
		{
			opp_num += 1;
			opp_sum += int_num;
			average_opp = opp_sum / opp_num;
		}
		else
		{
			pair_num += 1;
			pair_sum += int_num;
			average_pair = pair_sum / pair_num;
		}
	}
	printf("opp:%d pair:%d\n", opp_num, pair_num);
	printf("the average of opp is:%f\n,the average of pair is:%f", average_opp, average_pair);
	return 0;
}

4.使用if else语句编写一个程序读取输入,读到#停止。用感叹号代替句号,用两个感叹号代替原来的感叹号,最后报告进行了多少次替代。
 

/*4*/
#include<stdio.h>
#define STOP '#'
#define GANTAN '!'
#define JUHAO '.'
int main()
{
	char ch;
	int count = 0;
	while ((ch = getchar()) != STOP)
	{
		if (ch == '.')
		{
			putchar(GANTAN);
			count++;
		}
		else if (ch == '!')
		{
			putchar(GANTAN);
			putchar(GANTAN);
			count++;
		}
		else
			putchar(ch);
	}
	printf("exchange time:%d", 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值