【发布时间】:2021-10-07 10:12:59
【问题描述】:
更新:我意识到在 C 中我初始化了单词 counter 1。(我试图删除查询但我不被允许):/
为了尝试学习编码,我注册了 CS50 和 PSET2,有一个名为“可读性”的练习。我正在尝试使用 JavaScript 重新创建程序。根据提供的说明,输入的输出应该是 55 个单词,但我得到了 54 个。
我的 For 循环 正在遍历数组的每个元素,如果它找到一个空格,它将给单词计数器加 1(我的猜测是它不计算最后一个单词,因为它以“.”结尾)
JavaScript 代码:
let text = "It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him."
let words = 0;
let textArray = Array.from(text);
//Words
for (let i = 0; i < textArray.length; i++){
if (textArray[i] == " "){
words ++;
}
}
console.log("Words: " + words);
C 程序代码
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(void)
{
//Ask user for text
string text = get_string("Text: ");
//define variables
int letters = 0;
int words = 1;
int sentences = 0;
//loop to analyze text
for (int i = 0; i < strlen(text); i++)
{
//count letters
if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z'))
{
letters++;
}
//count words
else if (text[i] == ' ')
{
words++;
}
//count sentences
else if ((text[i] == '.') || (text[i] == '?') || (text[i] == '!'))
{
sentences++;
}
}
printf("Words: %i\n", words);
//math calculation (third rule)
float l = 100 * ((float) letters / (float) words);
float s = 100 * ((float) sentences / (float) words);
//printf("l: %i\n", (int) round(l));
//printf("s: %i\n", (int) round(s));
//grade index formula
float grade = (0.0588 * l) - (0.296 * s) - 15.8;
if (grade >= 16)
{
printf("Grade 16+\n");
}
else if (grade < 1)
{
printf("Before Grade 1\n");
}
else
{
printf("Grade %i\n", (int) round(grade));
}
}
【问题讨论】:
-
您的代码只有
54空格。结果是正确的。 -
想想
This is a test这个句子有多少个空格...以及有多少个单词。 -
感谢您的回复,我似乎不明白的是它与 C 中的句子完全相同,并且代码输出 55 个单词,任何关于为什么 C 得到与 JavaScript 不同的数字的问题输入相同?
-
我用你的 C 代码得到54,而不是 55
-
可以看到已经初始化了words=1
标签: javascript c cs50