Δημοσιεύτηκε: 02 Μαρ 2012, 21:51
από migf1
Ilias95 έγραψε:
13.
Εκφώνηση:
Spoiler: show
Write a program that calculates the average world length for a sentence.
For simplicity, your program should consider a punctuation mark to be part of the word to wich it is attached.
Display the average word length to one decimal place.

Λύση:
Spoiler: show
Μορφοποιημένος Κώδικας: Επιλογή όλων
#include <stdio.h>

int main(void)
{
char ch;
int words = 1, digits = 0;

printf("Enter a sentence: ");

while ((ch = getchar()) != '\n') {
if (ch == ' ')
words++;
else
digits++;
}

printf("Avarage word length: %.1f", (float) digits / words);

return 0;
}

Με αφορμή την άσκηση, μια ολοκληρωμένη υλοποίηση που θεωρεί (και μετράει) λέξεις μονάχα όσες αποτελούνται από γράμματα ή/και αριθμούς...

Μορφοποιημένος Κώδικας: Επιλογή όλων
#include <stdio.h>
#include <ctype.h> /* for isalnum() */

int main( void )
{
int ch = '\0';
int wcount = 0, letcount = 0;

printf("Enter a sentence: ");

for (;;) /* infinite loop */
{
ch = getchar();
if ( isalnum(ch) )
letcount++;
else {
if ( letcount ) /* ignore leading blanks */
wcount++;
/* ignore invalid (non-word) letters */
while ( '\n' != ch && !isalnum(ch=getchar()) )
;
if ( '\n' == ch )
break; /* exit infinite loop */
letcount++; /* count any last valid letter */
}
}

printf( "%d word(s), %d letter(s)\n", wcount, letcount );
printf( "Avarage word length: %.1f\n", !wcount ? 0 : (float)letcount/wcount );

return 0;
}