Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

คำนวณความยาวเฉลี่ยของคำในประโยคด้วย while loop ใน C


โจทย์

รับประโยคจากผู้ใช้ คำนวณความยาวเฉลี่ยของคำ (เฉลี่ยตัวอักษรต่อคำ)

อัลกอริทึม

  1. รับประโยคเก็บใน string
  2. วนนับ: ตัวอักษร (charCount) และ คำ (wordCount เริ่มที่ 1)
  3. เจอ space -> wordCount++
  4. คืนค่า 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