c primer plus(五版)編程練習-第七章編程練習
阿新 • • 發佈:2017-05-07
兩個感嘆號 nal getchar putc 進制 類型 運算 pre 重做
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; }
c primer plus(五版)編程練習-第七章編程練習