构建计算函数中字母的函数时出现的问题 - Cs50
Problem in building a function that counts the letters in a function - Cs50
我正在获取 'letter' 的整个字符串 s 的整数,我的 'if' 语句中的条件似乎没有正确读取 - 我的语法不正确吗?
我得到用户输入:
string s = get_string("Text here: ");
函数如下:
int letter_count(string s)
{
int i =0;
int len = strlen(s);
int letter = 0;
while(i < len)
{
if (s[i] != '[=11=]' || s[i] != '.' || s[i] != ',' || s[i] != '!' || s[i] != '?')
{
letter++;
}
i++;
}
return letter;
}
然后调用函数:
int letter = letter_count(s);
printf("letter Count: %i\n", letter);
if (s[i] != '[=10=]' || s[i] != '.' || s[i] != ',' || s[i] != '!' || s[i] != '?')
永远正确。因为任何字符要么不是“.”或不 ”,”。您希望哪个字母同时出现?
您想检查当前字母是否为“不是”。与“不”与“不!”。
即
if (s[i] != '[=11=]' && s[i] != '.' && s[i] != ',' && s[i] != '!' && s[i] != '?')
尝试使用 AND
更改 OR 运算符
几乎正确,你必须将参数类型更改为char*,默认库中没有字符串类型。 (Documentation of string library).
修改后的工作示例:
#include <stdio.h>
#include <string.h>
int letter_count (char* s)
{
int i = 0;
int len = strlen (s);
int letter = 0;
while (i < len)
{
if (s[i] != '[=10=]' && s[i] != '.' && s[i] != ',' && s[i] != '!'
&& s[i] != '?')
{
letter++;
}
i++;
}
return letter;
}
int main ()
{
char my_word[] = "Sample word";
printf ("'%s' have %d letters",my_word, letter_count (my_word));
return 0;
}
输出:
'Sample word' have 11 letters
我正在获取 'letter' 的整个字符串 s 的整数,我的 'if' 语句中的条件似乎没有正确读取 - 我的语法不正确吗?
我得到用户输入:
string s = get_string("Text here: ");
函数如下:
int letter_count(string s)
{
int i =0;
int len = strlen(s);
int letter = 0;
while(i < len)
{
if (s[i] != '[=11=]' || s[i] != '.' || s[i] != ',' || s[i] != '!' || s[i] != '?')
{
letter++;
}
i++;
}
return letter;
}
然后调用函数:
int letter = letter_count(s);
printf("letter Count: %i\n", letter);
if (s[i] != '[=10=]' || s[i] != '.' || s[i] != ',' || s[i] != '!' || s[i] != '?')
永远正确。因为任何字符要么不是“.”或不 ”,”。您希望哪个字母同时出现?
您想检查当前字母是否为“不是”。与“不”与“不!”。
即
if (s[i] != '[=11=]' && s[i] != '.' && s[i] != ',' && s[i] != '!' && s[i] != '?')
尝试使用 AND
更改 OR 运算符几乎正确,你必须将参数类型更改为char*,默认库中没有字符串类型。 (Documentation of string library).
修改后的工作示例:
#include <stdio.h>
#include <string.h>
int letter_count (char* s)
{
int i = 0;
int len = strlen (s);
int letter = 0;
while (i < len)
{
if (s[i] != '[=10=]' && s[i] != '.' && s[i] != ',' && s[i] != '!'
&& s[i] != '?')
{
letter++;
}
i++;
}
return letter;
}
int main ()
{
char my_word[] = "Sample word";
printf ("'%s' have %d letters",my_word, letter_count (my_word));
return 0;
}
输出:
'Sample word' have 11 letters