1.编写一个程序。该程序读取输入直到遇到#字符,然后报告读取的空格数目、读取的换行符数目以及读取的所有其他字符数目。
#include<stdio.h> #include<ctype.h> int main(void){ char ch; int count1,count2,count3; count1 = count2 = count3 = 0; printf("Enter text to be analyzed(#to terminate):\n"); while((ch = getchar()) != ‘#‘){ if ( ch == ‘\n‘){ count1++; } else if(isspace(ch)){ count2++; } else if (!isspace(ch)){ count3++; } } printf("换行数量%d,空格数量%d,其他字符数量%d",count1,count2,count3); return 0; }
2.编写一个程序。该程序读取输入直到遇到#字符。使程序打印每个输入的字符以及它的十进制ASCII 码。每行打印8 个字符/编码对。建议:利用字符计数和模运算符(%)在每8 个循环周期时打印一个换行符。
#include<stdio.h> #define STOP ‘#‘ int main(void){ char ch; int length = 1; printf("Enter text to be analyzed(#to terminate):\n"); while((ch = getchar()) != STOP){ if(length%8==0){ printf("\n"); } printf("%c/%d ",ch,ch); length++; } return 0; }
3.编写一个程序。该程序读取整数,直到输入0。输入终止后,程序应该报告输入的偶数(不包括0)总个数、偶数的平均值,输入的奇数总个数以及奇数的平均值。
#include<stdio.h> int main(void){ int num,even_num,odd_num; double even_count,odd_count;//必需定义为double类型,否则打印平均值会出错 even_num = odd_num = 0; even_count = odd_count = 0.0 ; printf("Enter int to be analyzed(0 to terminate):\n"); while (scanf("%d", &num) == 1 && num != 0){ if (num%2 == 0){ even_num++; even_count +=num; } else { odd_num++; odd_count +=num; } } if (even_count > 0) printf("Even have %d, even average is %.2f\n",even_num,even_count / even_num); if (odd_num > 0) printf("Odd have %d,odd average is %.2f",odd_num,odd_count/odd_num); return 0; }
4.利用if else 语句编写程序读取输入,直到#。用一个感叹号代替每个句号,将原有的每个感叹号用两个感叹号代替,最后报告进行了多少次替代。
#include<stdio.h> #define STOP ‘#‘ int main(void){ char ch; int i; i = 0; while((ch = getchar()) != STOP){ if (ch == ‘.‘){ putchar(‘!‘); i++; } else if (ch == ‘!‘){ putchar(ch); putchar(ch); i++; } else { putchar(ch); } } printf("\n"); printf("count %d",i); return 0; }
5.用switch 重做练习3。
#include<stdio.h> int main(void){ int num,even_num,odd_num; double even_count,odd_count;//必需定义为double类型,否则打印平均值会出错 even_num = odd_num = 0; even_count = odd_count = 0.0 ; printf("Enter int to be analyzed(0 to terminate):\n"); while (scanf("%d", &num) == 1 && num != 0){ switch (num%2){ case 0: even_num++; even_count +=num; break; case 1: odd_num++; odd_count +=num; break; } } if (even_count > 0) printf("Even have %d, even average is %.2f\n",even_num,even_count / even_num); if (odd_num > 0) printf("Odd have %d,odd average is %.2f",odd_num,odd_count/odd_num); return 0; }
时间: 2024-11-02 23:22:04