Đề bài
Nhập câu tại runtime, tính độ dài trung bình của các từ trong câu.
Thuật toán
BẮT ĐẦU
B1: Khai báo char, int, double
B2: Nhập câu
B3: Vòng lặp while đọc từng ký tự cho đến '\n'
Gọi hàm tính độ dài trung bình
B4: In kết quả
B5: Hàm calculatewordlength:
- Khởi tạo charcount=0, wordcount=1
- While *stmt != '\n':
Nếu *stmt != ' ' → charcount++
Ngược lại (gặp space) → wordcount++
stmt++
- Trả về (double)charcount / wordcount
KẾT THÚC
Chương trình hoàn chỉnh
#include <stdio.h>
#include <string.h>
double calculatewordlength(const char *stmt);
int main() {
char stmt[100];
int i = 0;
double avglen;
printf("Nhập câu: ");
while ((stmt[i] = getchar()) != '\n')
i++;
stmt[i] = '\n';
avglen = calculatewordlength(stmt);
printf("Độ dài trung bình từ: %f\n", avglen);
return 0;
}
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;
}
Kết quả chạy
Nhập câu: Tutorials Point is the best resource for online education
Độ dài trung bình từ: 5.444444