gpt4 book ai didi

c - .C语言中元音计数函数的难点

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:51 26 4
gpt4 key购买 nike

尝试为测试练习构建元音计数函数,但我是编码新手,无法弄清楚如何让字符指针正常工作。我做错了什么?

int vowelCount(int index, char phrase[])
{

int count = 0;
if(phrase[index] == '\0')
{
return 0;
}
if(phrase[index] == 'a' || phrase[index] == 'e' || phrase[index] == 'i' || phrase[index] == 'o' || phrase[index] == 'u')
{
count = count + 1;
}
if(phrase[index] == 'A' || phrase[index] == 'E' || phrase[index] == 'I' || phrase[index] == 'O' || phrase[index] == 'U')
{
count = count + 1;
}

vowelCount(index + 1, phrase);
return count;
}


int main (void)
{

char array[1000];
int index = 0;
char inputPhrase;
printf("Please enter a phrase: ");
scanf("%c",&inputPhrase);

while(inputPhrase != '\n')
{
array[index] = inputPhrase;
index = index + 1;
scanf("%c",&inputPhrase);
}
array[index] = '\0';
index = 0;
while(array[index] != '\0')
{
printf("%c",array[index]);
index = index + 1;
}
index = 0;
int numberOFvowels = vowelCount(index,array);

printf("\n\nThere are %i vowels in the phrase.",numberOFvowels);
}

最佳答案

在您的计数函数中,您基本上放弃了递归结果,只需将其添加到结果中即可:

int vowelCount(int index, char phrase[]) {
int count = 0;
if(phrase[index] == '\0')
{
return 0;
}
if(phrase[index] == 'a' || phrase[index] == 'e' || phrase[index] == 'i' || phrase[index] == 'o' || phrase[index] == 'u')
{
count = count + 1;
}
if(phrase[index] == 'A' || phrase[index] == 'E' || phrase[index] == 'I' || phrase[index] == 'O' || phrase[index] == 'U')
{
count = count + 1;
}

return count + vowelCount(index + 1, phrase); // add the result together here
}

但是,除非您尝试练习递归,否则以递归方式进行此计数是没有意义的,只需制作一个元音表并遍历字符串即可,这很容易编写且易于理解:

static int table[256] = {
['a']=1,['e']=1,['i']=1,['o']=1,['u']=1,
['A']=1,['E']=1,['I']=1,['O']=1,['U']=1
};
int vowelCount(const char *phrase) {
int count = 0;
while (*phrase) {
if (table[*phrase] == 1) {
count += 1;
}
phrase++;
}
return count;
}

关于c - .C语言中元音计数函数的难点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43314123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com