1.编写一个程序读取输入,读到#字符停止,然后报告读取的空格数、换行符数和所有其他字符的数量。
#include <stdio.h>
#define SPACE ' '
#define LINE '\n'
int main(void)
{
int sc = 0, lc = 0, oc = 0;
char ch;
while ((ch = getchar()) != '#')
{
if (ch == SPACE)
sc++;
else if (ch == LINE)
lc++;
else
oc++;
}
printf("空格字符数为%d,换行字符数为%d,其他字符数为%d\n",sc,lc,oc);
return 0;
}
2.编写一个程序读取输入,读到#字符停止。程序要打印每个输入的字符以及对应的ASCII码(十进制)。一行打印8个字符。建议:使用字符计数和求模运算符(%)在每8个循环周期时打印一个换行符。
#include <stdio.h>
#define LINE 8
int main(void)
{
int count = 0;
char ch;
while ((ch = getchar()) != '#')
{
count++;
printf("%c %d ", ch, ch);
if (count%LINE == 0)
printf("\n");
}
return 0;
}
3.编写一个程序,读取整数直到用户输入 0。输入结束后,程序应报告用户输入的偶数(不包括 0)个数、这些偶数的平均值、输入的奇数个数及其奇数的平均值。
#include <stdio.h>
int main(void)
{
int even_num = 0, odd_num = 0, even_sum = 0, odd_sum = 0, integer;
printf("enter integer(0 to quit)\n");
while (scanf("%d", &integer) == 1 && integer != 0)
{
if (integer % 2 == 0)
{
even_num++;
even_sum += integer;
}
else
{
odd_num++;
odd_sum += integer;
}
printf("enter integer(0 to quit)\n");
}
printf("even number is %d and even average is %.1f\n",even_num,(float)even_sum/even_num);
printf("odd number is %d and odd average is %.1f\n", odd_num, (float)odd_sum / odd_num);
return 0;
}
4.使用if else语句编写一个程序读取输入,读到#停止。用感叹号替换句号,用两个感叹号替换原来的感叹号,最后报告进行了多少次替换。
#include <stdio.h>
int main(void)
{
int count = 0;
char ch;
printf("enter character(# to quit)\n");
while ((ch=getchar())!='#')
{
if (ch == '.')
{
count++;
printf("!");
}
else if (ch == '!')
{
count++;
printf("!!");
}
else
printf("%c", ch);
}
printf("\nreplacement times is %d\n", count);
return 0;
}
5.使用switch重写练习4。
#include <stdio.h>
int main(void)
{
int count = 0;
char ch;
printf("enter character(# to quit)\n");
while ((ch=getchar())!='#')
{
switch (ch)
{
case '.':count++, printf("!")