2014-10-27 45 views
-1

我必须编写原型和实现一个C++函数, 接收一个字符,如果字符是元音则返回true,否则返回false。元音 包括以下字符'a'的大写和小写。 'e','i','o'和'u'。编写一个原型函数(C++)

我已经写

bool vowelOrNot(char x) 
{ if(x="a" or "e" or "i" or "o" or "u") 
     cout<<"true"<<endl; 

    else 
     cout<<"false""<<endl; 
} 

我写或者因为我不知道该怎么做这里的线,我是正确的我的功能?

+0

你想要一个答案,就好像这是伪代码,或者如果这是C++? – Drax 2014-10-27 16:02:36

+1

这不是有效的C++。 '或'不是一个关键字(查看'||'),并且不使用'='测试相等性(查看'==')。另外,你的函数假设返回一个'bool',但你不返回任何东西。 – Sean 2014-10-27 16:03:22

+3

我会为此使用switch语句。 – 2014-10-27 16:04:04

回答

0
bool vowelOrNot(char x) //x must be lowercase for the function to work as expected 
{ if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u') //== for comparing and single quotes for a char. 
    //|| is the logical OR 
    { 
     cout<<"true"<<endl; 
     return true; //return true to function caller 
    } 
    else 
     cout<<"false"<<endl; 
    return false;//return false to function caller 
} 
+0

我知道这些或迹象,但我如何将它们写在我的键盘上?任何帮助?并且应该将cout语句放在这个函数或主函数中,因为我在这个函数中需要做的事情是返回true或flase。 – user3531022 2014-10-27 16:14:51

+0

@ user3531022,回车键上方的按钮?如果它被放置在这里或'main'中,'cout'不关心。如果在'main'中,使用'cout <<“函数返回”<< vowelOrNot(yourchar);' – 2014-10-27 16:20:12

+0

@ user3531022 shift + \对我来说 – 2014-10-27 16:29:07

-1

试试这个:

bool vowelOrNot(char x) 
    { if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u' || x=='A' || x=='E' || x=='I' || x=='O' || x=='U') 
     { 
      cout<<"true"<<endl; 
      return true; 
      } 

     else 
     { 
      cout<<"false"<<endl; 
      return false; 
     } 
    } 
+0

回报在哪里? – 2014-10-27 16:04:23

+0

错过了。编辑 – 2014-10-27 16:06:31

0

您将需要一个测试,例如,

int 
main (int argc, char *argv[]) 
{ 
    bool test1 = vowelOrNot ('a'); 
    std::cout << test1 << " expected to be true" << std::endl; 

    return test1 == true ? EXIT_SUCCESS : EXIT_FAILURE;  
} 

当然,测试是不完整的。但是你必须为所有可能的输入数据编写测试。

3

由于没有一个建议吧,这里是使用switch语句的解决方案:

bool vowelOrNot(char x) 
{ 
    switch (x) 
    { 
     case 'a': 
     case 'A': 
     case 'e': 
     case 'E': 
     case 'i': 
     case 'I': 
     case 'o': 
     case 'O': 
     case 'u': 
     case 'U': 
      return true; 

     default: 
      return false; 
    } 
} 

我使用toupper转换输入和只检查的情况下首都考虑。

0

小心使用单词原型。 C++函数原型是一种声明,通常发生在main()之前的文件顶部或模块的头文件中(可能前者在您的情况下)。它看起来像这样:

bool vowelOrNot(char); 

你有什么是实现,但你有不正确的语法。 “或”不是C++中的关键字。使用“||”。另外,“==”是等于比较运算符而不是“=”。我建议至少阅读以下文档:http://www.cplusplus.com/doc/tutorial/control/

此外,我注意到你的函数返回一个布尔值,但是你打印每个布尔值的单词而不是返回它。如果您需要打印这些单词,则应根据函数的返回值在别处处理。

我推荐的解决方案如下:

#include <string> 
#include <cctype> 
using namespace std; 

bool vowelOrNot(char); 

const string VOWELS = "aeiou"; 

int main 
{ 
    //some code that uses vowelOrNot, perhaps printing true and false 
} 

bool vowelOrNot(char c) 
{ 
    return VOWELS.find(tolower(c)) != string::npos; 
} 

最后,我建议重命名功能is_vowel()或类似的东西更加清晰和简洁的有关功能的目的。

希望这会有所帮助!