1、编写一个程序。该程序读取输入直到遇到#字符,然后报告读取的空格数目、读取的换行符数目以及读取的所有其他字符数目。
#include<stdio.h>
int main(void)
{
int space=0,newline=0,others=0;
char a;
printf("Please input a string end by #:");
while((a=getchar()) != '#')
if(a == ' ') space++;
else if (a == '\n') newline++;
else others++;
printf("space: %d,newline: %d,others: %d\n",space,newline,others);
return(0);
}
2、编写一个程序,该程序读取输入直到遇到#字符。使程序打印每个输入的字符以及它的十进制ASCII码。每行打印8个字符,编码对。建议:利用字符计数和模运算符(%)在每8个循环周期时打印一个换行符。
#include<stdio.h>
int main(void)
{
char a;
int i;
printf("Please input a string end by #:");
for(i = 1; (a = getchar()) != '#'; i++)
{
printf("%c--%d\t",a,a);
if(i%8 == 0) printf("\n");
}
printf("\n");
return(0);
}
3、编写一个程序。该程序读取整数,直到输入0。输入终止后,程序应该报告输入的偶数(不包括0)总个数、偶数的平均值,输入的奇数总个数以及奇数的平均值。
#include<stdio.h>
int main(void)
{
int i_even = 0, sum_even = 0, i_odd = 0, sum_odd = 0, num;
printf("Please input numbers (0 to quit):");
while(1)
{
scanf("%d",&num);
if (num == 0) break;
if (num % 2 == 0) {i_even++; sum_even += num;}
else {i_odd++; sum_odd += num;}
}
printf("even number's count: %d\n",i_even);
printf("even number's sum : %d\n",sum_even);
printf("odd number's count: %d\n",i_odd);
printf("odd number's sum : %d\n",sum_odd);
return(0);
}
4、利用if else语句编写程序读取输入,直到#。用一个感叹号代替每个句号,将原有的每个感叹号用两个感叹号代替,最后报告进行了多少次替代。
#include<stdio.h>
int main(void)
{
int a=0,b=0;
char ch;
printf("Please input a string end by #:");
while((ch = getchar()) != '#')
{
if(ch == '.') {putchar('!'); a++;}
else if(ch == '!') {putchar('!');putchar('!'); b++;}
else putchar(ch);
}
printf("\nthe times of '.' replaced by '!': %d\n",a);
printf("the times of '!' replaced by '!!': %d\n",b);
return(0);
}
5、用switch重做练习3。
#include<stdio.h>
int main(void)
{
int i_even = 0, sum_even = 0, i_odd = 0, sum_odd = 0, num;
printf("Please input numbers (0 to quit):");
while(1)
{ </