编写原型函数(c++)

Writing a prototype function(c++)

本文关键字:c++ 函数 原型      更新时间:2023-10-16

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

我已经写了

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

我写了,或者因为我不知道怎么写,我的函数正确吗?

正如没有人建议的那样,这里有一个使用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来转换输入,并且在这种情况下只检查大写字母。

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
}

您将需要一个测试,例如

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;    
}

当然,测试还没有完成。但是您必须为所有可能的输入数据编写测试。

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

bool vowelOrNot(char);

您所拥有的是实现,但语法不正确。"or"不是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()或类似的名称,以便更清楚、简洁地说明函数的用途。

希望这能有所帮助!

试试这个:

    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;
        }
    }