c程序设计语言 课后习题

来源:互联网 发布:linux 部署gitlab 编辑:程序博客网 时间:2024/04/30 08:09

练习1-12 编写一个程序,以每行一个单词的形式打印其输入。

做法:当状态从单词内变为单词外的时候,输出‘\n’

#include <stdio.h>#define IN 1#define OUT 0int main(void){int nw = 0;int lastState = OUT;int state = OUT;int ch;while ((ch = getchar()) != EOF){if (ch == ' ' || ch == '\t' || ch == '\n'){lastState = state;state = OUT;}else{printf("%c",ch);lastState = state;state = IN;}if(lastState == IN && state == OUT){printf("\n");}}return 0;}
上面这个方法是我自己想的,虽然可以实现,但是不是很好。其实变量lastState可以省略掉,因为在状态改变前,state还保留着之前的状态。所以代码可以改成下面这种形式

#include <stdio.h>#define IN 1#define OUT 0int main(void){int nw = 0;int state = OUT;int ch;while ((ch = getchar()) != EOF){if (ch == ' ' || ch == '\t' || ch == '\n'){if(state == IN)printf("\n");state = OUT;}else{printf("%c",ch);state = IN;}}return 0;}

练习 1-13

编写一个程序,打印输入单词长度的直方图。水平方向的直方图比较容易,垂直方向的直方图则要困难些。

想法:

1、统计单词个数,并统计长度。

2、输出直方图

#include <stdio.h>#define IN 1#define OUT 0#define MAX 10  //单词个数的最大值void show(int wordCount, int wordLength[]);int main(){int state = OUT;int ch;int wordCount = 0;int wordLength[MAX+1] = {0};while ((ch = getchar()) != EOF && wordCount < MAX){if(ch == ' ' || ch == '\t' || ch == '\n'){state = OUT;}else if(state == OUT){state = IN;wordCount ++;}if(state == IN){++wordLength[wordCount];}}show(wordCount, wordLength);scanf("%d",&ch);return 0;}


输出水平直方图:

void show(int wordCount, int wordLength[]){int i, j;for(i = 1; i <= wordCount; i++){for(j = 0; j < wordLength[i]; j++){printf("*");}printf("\n");}}


输出垂直直方图:

void show(int wordCount, int wordLength[]){int i, j;int maxLength = 0; int currentLength = 0;for(i = 1; i <= wordCount; i++){//找出最长的那一个if(wordLength[i] > maxLength){maxLength = wordLength[i];}}currentLength = maxLength;while(currentLength > 0){for(j = 1; j <= wordCount; j++){if(wordLength[j] >= currentLength){printf("*\t");}else{printf(" \t");}}-- currentLength;printf("\n");}}


0 0
原创粉丝点击