C Primer Plus 第七章:分支和跳转 编程答案

本文提供了一系列C语言编程练习,包括读取输入直到特定字符、字符ASCII码显示、整数输入统计、字符替换、字符计数、工资计算、税收计算和商品订购等场景,涉及到if-else、switch语句以及循环结构的应用。
摘要由CSDN通过智能技术生成

7.16 编程练习

  1. 编写一个程序读取输入,读到#字符停止,然后报告读取的空格数、换行数和其他所有字符的数量。
#include <stdio.h>
int main()
{
	int num_n = 0;
	int num_space = 0;
	int num_else = 0;
	char ch;
	while (scanf("%c", &ch) == 1)
	{
		if (ch == '#')
			break;
		else if (ch == ' ')
			num_space++;
		else if (ch == '\n')
			num_n++;
		else
			num_else++;
	}
	printf("num_n:%3d\num_else:%3d\nnum_space:%3d\n", \
	num_n, num_else, num_space);
	return 0;
}
  1. 编写一个程序读取输入,读到#字符停止。程序要打印每个输入的字符以及对应的ASCII码(十进制)。一行打印8个字符。建议:使用字符计数和求模运算符(%)在每8个循环周期时打印一个换行符。
#include <stdio.h>
#define SIZE 8
int main()
{
	char ch;
	int num = 1;
	while (scanf("%c", &ch) == 1)
	{
		if (ch == '#')
		{
			break;
		}
		else
		{
			if (num % SIZE == 0)
				printf("%-5d\n",ch);
			else
				printf("%-5d",ch);
			num++;
		}
	}
	return 0;
}
  1. 编写一个程序,读取整数直到用户输入 0。
    输入结束后,程序应报告用户输入的偶数(不包括 0)个数、
    这些偶数的平均值、输入的奇数个数及其奇数的平均值
#include <stdio.h>
int main()
{
	int num_even = 0;
	int num_odd = 0;
	int sum_even =0;
	int sum_odd = 0;
	int num;
	while (scanf("%d", &num) == 1)
	{
		if (num == 0)
		{
			break;
		}
		else if (num % 2 == 0)
		{
			num_even++;
			sum_even +=num;
		}
		else
		{
			num_odd++;
			sum_odd +=num;
		}
	}
	printf("num_even:%-5d,num_odd:%-5d\n", num_even, num_odd);
	printf("sum_even:%-5d,sum_odd:%-5d\n", sum_even, sum_odd);
	printf("ave_even:%-5d,ave_odd:%-5d\n",sum_even / num_even, \
	sum_odd / num_odd);
	return 0;
}
  1. 使用if else语句编写一个程序读取输入,读到#停止。用感叹号代替句号,用两个感叹号代替原来的感叹号,最后报告进行了多少次替代。
#include <stdio.h>
int main()
{
	int i = 0, j = 0;
	char ch;
	while ((ch = getchar()) != '#')
	{
		if (ch == '.')
		{
			putchar('!');
			i++;
		}
		else if (ch == '!')
		{
			putchar('!');
			putchar('!');
			j++;
			
		}
		else
		{
			putchar(ch);
		}
	}
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值