以下是一个用C语言编写的程序,用于统计输入字符串中平均每句话包含的单词个数:
#include <stdio.h>
#include <string.h>
int countWords(char *sentence) {
int words = 0;
char *token = strtok(sentence, " ,.");
while(token != NULL) {
words++;
token = strtok(NULL, " ,.");
}
return words;
}
int main() {
char input[1000];
printf("请输入字符串:\n");
fgets(input, sizeof(input), stdin);
int sentences = 0; // 句子数量
int words = 0; // 单词数量
char *sentence = strtok(input, ".");
while (sentence != NULL) {
sentences++;
words += countWords(sentence);
sentence = strtok(NULL, ".");
}
// 计算平均每句话包含的单词个数
float average = (float) words / sentences;
printf("平均每句话包含的单词个数:%.2f\n", average);
return 0;
}
这个程序首先定义了一个countWords函数来统计每个句子中的单词个数。然后在main函数中,使用fgets函数获取用户输入的字符串,并使用strtok函数按句号将字符串分割成句子。然后对于每个句子,调用countWords函数计算单词数量,并统计句子数量和单词数量。最后,通过除法计算平均每句话包含的单词个数,并将结果打印出来。