我写了一些代码来打印出输入到给定文本中所需数量的字母。由于某些原因,在9个字母之后,它似乎会增加1,并且会稍微超出输入中给出的字母数量。任何建议,不胜感激:)
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
// Function to count letters
int count_letter(string text)
{
// Declaring function variables
int lettercount = 0;
int number_of_letters;
int spaces = 0;
int letter_all;
// Getting length of the text
number_of_letters = strlen(text);
// Counting the letters in the text inputted
for(lettercount = 0; lettercount < number_of_letters; lettercount++)
{ // If text is from a-z then count the text
if(isalpha(text[lettercount]))
lettercount++;
// If text is equal to space then add up the spaces
else if(isspace(text[lettercount]))
spaces++;
// Minus the spaces from the lettercount
letter_all = lettercount - spaces;
}
return letter_all;
}
int main(void)
{
// Getting a string of Text and storing it in a variable
string passage = get_string("text: ");
{
printf("%i letter(s)\n", count_letter(passage));
}
}
答案 0 :(得分:2)
当您执行letter_all = lettercount - spaces
时,您要在字母数中减去空格数。因此,如果您使用字符串“ he llo”,则有5个字母和1个空格,并且您正在执行5-1。然后您的程序将打印4,这是不正确的。因此,您应该只打印出lettercount以获取字母编号。
这就是您的功能。
int count_letter(string text)
{
// Declaring function variables
int lettercount = 0;
int number_of_letters;
int spaces = 0;
int letter_all,i;
// Getting length of the text
number_of_letters = strlen(text);
// Counting the letters in the text inputted
for(i = 0; i < number_of_letters; i++)
{ // If text is from a-z then count the text
if(isalpha(text[i]))
lettercount++;
}
return lettercount;
}
答案 1 :(得分:0)
在您的函数中,应删除此行letter_all = lettercount-减少实际字母数量的空格
// Libraries
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
int count_letter(string text)
{
// Declaring function variables
int lettercount = 0;
int number_of_letters;
int spaces = 0;
int letter_all,i;
// Getting length of the text
number_of_letters = strlen(text);
// Counting the letters in the text inputted
for(i = 0; i < number_of_letters; i++)
{ // If text is from a-z then count the text
if(isalpha(text[i]))
lettercount++;
}
return lettercount;
}
int main(void)
{
// Getting a string of Text and storing it in a variable
string passage = get_string("text: ");
{
printf("%i letter(s)\n", count_letter(passage));
}
}