C prime plus 第五版-第七章(控制语句)编程练习
c语言编程练习都为本人学习时的编写代码记录或学习笔记,若有不当之处欢迎指正,感激不尽(其中题型当然可能有其他编程设计方案,比如利用自定义函数等,因为我在操练基础,所以就不涉及,仅作记录)。
1.编写一个程序。该程序读取输入直到遇到#字符,然后报告读取的空格数目、读取的换行符数目以及读取的所有其他字符数目。
#include<stdio.h>
int main(void)
{
char ch;
int sp, li, t_or; //space ,line , total_others
t_or = li = sp = 0;
printf("Please input a string end by '#':\n");
while((ch = getchar()) != '#') {
if(ch == ' ')
sp++;
else if(ch == '\n')
li++;
else
t_or++;
}
printf("space=%d,line=%d,total_other=%d\n", sp, li, t_or);
return 0;
}
2.编写一个程序,该程序读取输入直到遇到#字符。使程序打印每个输入的字符以及它的十进制ASCII 码。每行打印 8 个字符,编码对。建议:利用字符计数和模运算符(%)在每 8 个循环周期时打印一个换行符。
//for 循环
#include<stdio.h>
int main(void)
{
char ch;
int co = 0; //count
printf("Please input a string end by '#':\n");
for(co = 1;(ch = getchar()) != '#'; co++) {
printf("%c,%d|| ", ch, ch);
if(co % 8 == 0)
printf("\n");
}
printf("\n");
return 0;
}
//while 循环
#include<stdio.h>
int main(void)
{
char ch;
int co = 0;
printf("Please input a string end by '#':\n");
while((ch = getchar()) != '#') {
co++;
printf("%c,%d|| ", ch, ch);
if(co % 8 == 0)
printf("\n");
}
printf("\n");
return 0;
}
3.编写一个程序。该程序读取整数,直到输入 0。输入终止后,程序应该报告输入的偶数(不包括0)总个数、偶数的平均值,输入的奇数总个数以及奇数的平均值。
#include<stdio.h>
int main(void)
{
int e, s_e, o, s_o, num;
s_o = s_e = o = e = 0;
//e-even(偶),o-odd(奇),s_e-sum_even,s_o-sum_odd
printf("Please input numbers(0 to quit!):\n");
while(scanf("%d", &num) == 1) {
if(num == 0)
break;
if(num % 2 == 0) {
e++;
s_e += num;
}
else {
o++;
s_o += num;
}
}
printf("e =%d,", e);
printf("s_e / e=%.1f\n",1.0 * s_e / e);
printf("o =%d,", o);
printf("s_o / o=%.1f\n",1.0 * s_o / o);
return 0;
}
4.利用 if else 语句编写程序读取输入,直到#。用一个感叹号代替每个句号,将原有的每个感叹号用两个感叹号代替,最后报告进行了多少次替代。
#include<stdio.h>
int main(void)
{
int i = 0, j = 0;
char ch;
printf("