[英]Issues with a string count, integers to float, Grade formula based on the number of letters, words, and sentences, in C
我正在編寫一個程序來生成字母、單詞和句子的數量,提供輸入文本。
使用這些值,我想根據一個公式生成一個數字(評估“可讀性”),其中字母、單詞和句子中的數字作為變量。
請參閱此代碼的最后一部分(對於等級公式)。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(void)
{
char str[1000];
int i=0, chr=0, st=1, sn=0;
printf("Text: ");
fgets(str, sizeof(str), stdin);
for( i = 0; str[i] != '\0' ; i++)
{
chr = chr + 1;
}
printf("%d letters\n", chr);
for (i = 0; i <= chr - 1; i++)
{
if (str[i] == ' ')
{
st = st + 1;
}
}
printf("%d words\n", st);
for (i = 0; i <= chr - 1; i++)
{
if (str[i] == '.' || str[i] == '!' || str[i] == '?')
{
sn = sn + 1;
}
}
printf("%d sentences\n", sn);
double L = (100.0 * chr / st);
double S = (100.0 * sn / st);
double grade = 0.0588 * L - 0.296 * S - 15.8;
if (grade <= 1)
{
printf("Before Grade 1\n");
}
else if (grade < 16)
{
printf("Grade %f\n", round(grade));
}
else
{
printf("Grade 16+\n");
}
}
我不知道為什么等級公式會產生奇怪的結果。
例如,
樣本輸入:
There are more things in Heaven and Earth, Horatio, than are dreamt of in your philosophy.
樣品 output:
92 letters
17 words
1 sentences
Grade 14
字母、單詞和句子並不奇怪——它們是意料之中的。 14級很奇怪,因為我期待9級。我無法識別模式,只是特征奇怪可以描述為等級的output總是大於預期值,對於1級以上的預期值。
to continue,
-Expected Grade 10 shows output Grade 16
-Expected Grade 8 shows output Grade 15
-Expected Grade 7 shows output Grade 14
-Expected Grade 5 shows output Grade 11
-Expected Grade 3 shows output Grade 10
-Expected Grade 2 shows output Grade 9
預期在 1 級之前的文本會產生預期的 output。
等級公式:
指數 = 0.0588 * L - 0.296 * S - 15.8
其中 L 是文本中每 100 個單詞的平均字母數,S 是文本中每 100 個單詞的平均句子數
總的來說,我不知道為什么等級公式沒有生成預期的 output。
我想,你對信的看法是錯誤的。 在您的input
中有一些空格字符、逗號字符等。因此您需要准確計算這句話中的字母數量(a、b、c、d、e、f 等)。
您可以使用 function isalpha
來計算字母的數量:
for( i = 0; str[i] != '\0' ; i++)
{
if(isalpha(str[i]))
chr = chr + 1;
}
然后其他for循環計算單詞和句子的數量,使用strlen(str)
代替chr - 1
for (i = 0; i < strlen(str); i++)
{
if (str[i] == ' ')
{
st = st + 1;
}
}
printf("%d words\n", st);
for (i = 0; i < strlen(str); i++)
{
if (str[i] == '.' || str[i] == '!' || str[i] == '?')
{
sn = sn + 1;
}
}
當我測試時,我得到了結果:
Text: There are more things in Heaven and Earth, Horatio, than are dreamt of in your philosophy.
72 letters
16 words
1 sentences
Grade 9.000000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.