【发布时间】:2022-08-04 05:15:26
【问题描述】:
我目前正在学习 cs50 课程(免费版,所以我没有同学或老师的反馈),我们被要求编写一个程序来读取用户输入的文本,并分析文本:
- 字母数
- 字数
- 句子数
- L = 平均每 100 个单词的字母数
- S = 平均每 100 个单词的句子数
- 年级 = (((0.0588) * L) - ((0.296) * S)) - 15.8)
示例文本:
“你喜欢这里还是那里?我不喜欢这里或那里。我在任何地方都不喜欢它们。”
我已经对代码进行了调试,它成功地计算了字母、单词和句子。
第一个问题出现在这里:
float calculate_avg_letters(int letters, int
words)
{
float L = ((letters) / (words)) * 100;
return (L);
}
我已经尝试了一切(我认为),从更改数据类型、重新排列括号、使用两个单独的函数先执行除法然后乘以结果变量、更改前一个变量的数据类型。逐步调试显示(字母 = 80)、(单词 = 21)和(句子 = 3),所以 L = ((80 / 21) * 100)。它应该是 ~380,但我能得到的最接近的是 300,并且大多数变体输出类似于 1.44e13
对于上下文,这是整个代码:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
float count_letters(string paragraph);
float count_words(string paragraph);
float count_sentences(string paragraph);
float calculate_avg_letters(int letters, int
words);
float calculate_avg_sentences(int sentences, int
words);
int calculate_grade_level(int L, int S);
int main(void)
{
string text = get_string(\"Text: \");
float letters = count_letters(text);
float words = count_words(text);
float sentences = count_sentences(text);
float L = calculate_avg_letters(letters,
words);
float S = calculate_avg_sentences(sentences,
words);
int grade = calculate_grade_level(L, S);
// print results
if (grade < 1)
{
printf(\"Before Grade 1\\n\");
}
else if (grade >= 16)
{
printf(\"Grade 16+\\n\");
}
else
{
printf(\"Grade %i\\n\", grade);
}
}
int calculate_grade_level(int L, int S)
{
int grade = (((0.0588 * L) - (0.296 * S)) -
15.8);
return round(grade);
}
float count_letters(string paragraph)
{
int length = strlen(paragraph);
float letters = 0;
for (int i = 0; i < length; i++)
{
if (isalpha(paragraph[i]))
letters++;
}
printf(\"%.1f letters\\n\", letters);
return letters;
}
float count_words(string paragraph)
{
int length = strlen(paragraph);
float words = 0;
for (int i = 0; i < length; i++)
{
if (paragraph[i] == \' \')
words++;
}
words = words + 1;
printf(\"%.1f words\\n\", words);
return words;
}
float count_sentences(string paragraph)
{
int length = strlen(paragraph);
float sentences = 0;
for (int i = 0; i < length; i++)
{
if (paragraph[i] == \'.\' || paragraph[i]
== \'!\' || paragraph[i] == \'?\')
{
sentences++;
}
}
printf(\"%.1f sentences\\n\", sentences);
return sentences;
}
float calculate_avg_letters(int letters, int
words)
{
float L = ((letters) / (words)) * 100;
return L;
}
float calculate_avg_sentences(int sentences, int
words)
{
float S = ((sentences / words) * 100);
return S;
}
-
欢迎来到堆栈溢出。请阅读How to Ask和minimal reproducible example,并尝试显示所有,但只有代码这是证明您所询问的具体问题所必需的。
-
非常简单...除法是使用整数(截断)完成的,然后转换并存储为浮点数。尝试使用 `float L = (float)words/letters * 100.0;