โจทย์
รับประโยคจากผู้ใช้ คำนวณความยาวเฉลี่ยของคำ (เฉลี่ยตัวอักษรต่อคำ)
อัลกอริทึม
- รับประโยคเก็บใน string
- วนนับ: ตัวอักษร (charCount) และ คำ (wordCount เริ่มที่ 1)
- เจอ space -> wordCount++
- คืนค่า charCount / wordCount
โปรแกรมตัวอย่าง
#include <stdio.h>
#include <string.h>
double avgWordLen(const char *str) {
int chars = 0, words = 1;
while(*str != '\0' && *str != '\n') {
if(*str != ' ') chars++;
else words++;
str++;
}
return (double)chars / words;
}
int main() {
char stmt[100];
int i = 0;
printf("Enter sentence: ");
while((stmt[i] = getchar()) != '\n' && i < 99) i++;
stmt[i] = '\0';
printf("Average word length: %.2f\n", avgWordLen(stmt));
return 0;
}
ผลลัพธ์
enter any statement: Tutorials Point is the best resource for online education average word length: 5.44