首頁 >後端開發 >C++ >寫一個C程序,使用while循環計算句子的平均單字長度

寫一個C程序,使用while循環計算句子的平均單字長度

WBOY
WBOY轉載
2023-08-28 18:25:061466瀏覽

寫一個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()) != &#39;</p><p>&#39;
       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 != &#39;</p><p>&#39;)
            if it trues enter into loop
            1.    if(*stmt != &#39; &#39;)
            2.    charcount++;
            3.    else if(*stmt == &#39; &#39;)
            4.    wordcount++;
            5.    stmt++;
         iii. return (double)charcount/wordcount;
STOP

程式

#include<stdio.h>
#include<string.h>
double calculatewordlength(const char *stmt);
int main(){
   char stmt[100];
   int i=0;
   double avglen;
   printf("enter any statement:");
   while((stmt[i]=getchar()) != &#39;</p><p>&#39;)
      i++;
   stmt[i]=&#39;</p><p>&#39;;
   avglen=calculatewordlength(stmt);
   printf("average length of word is:%f.</p><p> ", avglen);
}
double calculatewordlength(const char *stmt){
   int charcount=0;
   int wordcount=1;
   while(*stmt != &#39;</p><p>&#39;){
      if(*stmt != &#39; &#39;)
         charcount++;
      else if(*stmt == &#39; &#39;)
         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循環計算句子的平均單字長度的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除