问题
在运行时输入一个句子,并编写一段代码来计算句子中出现的单词的平均长度
解决方案
算法
STARTStep 1: declare character, int and double variablesStep 2: Enter any statementStep 3: while loop Check condition stmt[i]=getchar()) != '' True then enter into loop Increment I and call the function at step 5Step 4: Print the average length return by function From step 5Step 5: called function calculatewordlength i. declare and initialize charcount=0 and wordcount=1 ii. while loop check condition (*stmt != '
') 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#includedouble calculatewordlength(const char *stmt);int main(){ char stmt[100]; int i=0; double avglen; printf("enter any statement:"); while((stmt[i]=getchar()) != '') i++; stmt[i]='
'; avglen=calculatewordlength(stmt); printf("average length of word is:%f.
", avglen);}double calculatewordlength(const char *stmt){ int charcount=0; int wordcount=1; while(*stmt != '
'){ if(*stmt != ' ') charcount++; else if(*stmt == ' ') wordcount++; stmt++; } return (double)charcount/wordcount;}
登录后复制
输出
enter any statement:Tutorials Point is the best resource for online education average length of word: 5.444444444.
登录后复制
以上就是编写一个C程序,使用while循环计算句子的平均单词长度的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2585521.html