7.16 编程练习
- 编写一个程序读取输入,读到#字符停止,然后报告读取的空格数、换行数和其他所有字符的数量。
#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;
}
- 编写一个程序读取输入,读到#字符停止。程序要打印每个输入的字符以及对应的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;
}
- 编写一个程序,读取整数直到用户输入 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;
}
- 使用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);
}
}