编写一个C程序以使用while循环计算句子的平均单词长度
问题
在运行时输入一个句子并编写代码以计算句子中存在的单词的平均长度
解决方案
算法
START
Step 1: declare character, int and double variables
Step 2: Enter any statement
Step 3: while loop
Check condition stmt[i]=getchar()) != '\n'
True then enter into loop
Increment I and call the function at step 5
Step 4: Print the average length return by function
From step 5
Step 5: called function calculatewordlength
i. declare and initialize
charcount=0 and wordcount=1
ii. while loop
check condition (*stmt != '\n')
if it trues enter into loop
1. if(*stmt != ' ')
2. charcount++;
3. else if(*stmt == ' ')
4. wordcount++;
5. stmt++;
iii. return (double)charcount/wordcount;
STOP程序
#include输出结果#include double calculatewordlength(const char *stmt); int main(){ char stmt[100]; int i=0; double avglen; printf("输入任何语句:"); while((stmt[i]=getchar()) != '\n') i++; stmt[i]='\n'; avglen=calculatewordlength(stmt); printf("average length of word is:%f.\n ", avglen); } double calculatewordlength(const char *stmt){ int charcount=0; int wordcount=1; while(*stmt != '\n'){ if(*stmt != ' ') charcount++; else if(*stmt == ' ') wordcount++; stmt++; } return (double)charcount/wordcount; }
输入任何语句:nhooo.com is the best resource for online education average length of word: 5.444444444.
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西