2011-05-31 105 views
1

我只想使用递归计算字符串中的元音,但它不起作用。计算字符串中元音的数量

#include <stdio.h> 
#include <string.h> 

#define SETSIZ 10 

#define TRUE 1 
#define FALSE 0 
int is_empty(const char *set); 
int is_element(char vowel, const char *set); 
int is_vowel(const char *vowels, const char *set); 

int main(void) 
{ 
    int count = 0,i; 
    char vowels[11] = {'A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u', '\0'}, set[SETSIZ] = "mustafa"; 
    for(i=0;i<strlen(set);i++){ 
     if(is_vowel(vowels, set)) 
      count += 1; 
     } 
    printf("%s has %d vowels",set, count); 
    return(0); 
} 
int is_empty(const char *set) 
{ 
    return(set[0] == '\0'); 
} 
int is_element(char vowel, const char *set) 
{ 
    int ans; 
    if(is_empty(set)) 
     ans = FALSE; 
    else if (vowel == set[0]) 
     ans = TRUE; 
    else 
     ans = is_element(vowel, &set[1]); 
    return(ans); 
} 
int is_vowel(const char *vowels, const char *set) 
{ 
    int ans, i = 0; 

    if(is_empty(vowels)) 
     ans = FALSE; 
    else if(is_element(vowels[0], set)) 
    { 
     printf("**"); 
     ans = TRUE; 
    } 
    else 
    { 
     printf("--"); 
     ans = is_vowel(&vowels[1], set); 
     } 

    return(ans); 
} 
+0

在'main'中循环'set'(它看起来不在那个范围内),并且总是把相同的东西传递给'is_vowel'。你从不使用循环计数器'i'。 – 2011-05-31 11:24:28

+0

'set'在滚动区域中定义。我还认为它一开始没有定义。到OP:@paranoidgnu - 限制行长度为80个字符:) – pmg 2011-05-31 11:28:21

回答

0
  1. 你不遍历set因为你可能想要的。应该是:

    if(is_vowel(vowels, &set[i])) 
    
  2. 你的功能is_element()是绝对错误的,你可以把它改成:

    int is_element(char vowel, const char *set) 
    { 
        return (vowel == set[0]); 
    } 
    

甚至通过字符,而不是指向字符。

3

您的is_vowel代码存在问题。

int is_vowel(const char *vowels, const char *set) 
{ 
int ans, i = 0; 

if(is_empty(vowels))  //You are passing vowels which would never be empty. 
    ans = FALSE;   //Replace it with set character pointer. 
//Rest of the code 

整体概念,应用似乎是错的。我的哥们建议你重写code.There是整个代码错误的无数数量。

0

有一个简单的解决问题的方法:

#define VOWELS "aeiouAEIOU" 

size_t vcount(const char *s) 
{ 
     size_t i = 0; 

     while (s && *s) { 
       if (strchr(VOWELS, *s)) ++i; 
       ++s; 
     } 

     return i; 
} 

它可以很容易地转化成递归版本。

1

main中,您的for循环使用完全相同的参数多次调用is_vowel()

你可能想用一个简单的protoyype重写功能:

/* int is_vowel(const char *vowels, const char *set); */ 
int is_vowel(const char *vowels, int ch); 
1
#include <stdio.h> 



int vowel(char str[],int k) 
{ 
int count = 0; 
while(str[k]!='\0') 
{ 
    if(str[k] == 'a' || str[k] == 'e' || str[k] == 'i' || str[k] == 'o' || str[k] == 'u') 
     return 1 + vowel(str,k+1); 
    else 
     return 0 +vowel(str,k+1); 
} 
return 0; 
} 
void main() 
{ 
char x[50]; 
gets(x); 
printf("%d",vowel(x,0)); 
} 
0

可以使用此代码在python计数元音的数量:(S)

DEF元音:

if s == '': 
    return 0 # no vowels in the empty string 
elif s[0] in 'aeiouAEIOU': 
    return 1 + vowels(s[1:]) 
else: 
    return 0 + vowels(s[1:]) 

也可以使用一个变量,如vowel_list ='aeiouAEIOU '

相关问题