字母“A”、“E”、“I”、“O”和“U”称为元音。除这5个元音字母外的所有其他字母都称为辅音。
此程序假定用户将始终输入字母字符。
检查元音或辅音的程序
#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);
// evaluates to 1 if variable c is a lowercase vowel
lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
// evaluates to 1 if variable c is a uppercase vowel
uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
// evaluates to 1 (true) if c is a vowel
if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
else
printf("%c is a consonant.", c);
return 0;
}
输出
Enter an alphabet: G G is a consonant.
用户输入的字符存储在变量c中。
如果c是小写元音,则lowercase_vowel变量求值为1(真),而对于任何其他字符,则求值为0(假)。
同样,如果c是大写元音,则uppercase_vowel变量求值为1(真),而对于任何其他字符,则求值为0(假)。
如果lowercase_vowel或uppercase_vowel变量中任一为1(真),则输入的字符是元音。但是,如果lowercase_vowel和uppercase_vowel变量均为0,则输入的字符是辅音。
注意:此程序假定用户将输入一个字母。如果用户输入非字母字符,则显示该字符为辅音。
为了解决这个问题,我们可以使用isalpha()函数。isalpha()
函数检查字符是否为字母。
#include <ctype.h>
#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);
// evaluates to 1 if variable c is a lowercase vowel
lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
// evaluates to 1 if variable c is a uppercase vowel
uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
// Show error message if c is not an alphabet
if (!isalpha(c))
printf("Error! Non-alphabetic character.");
else if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
else
printf("%c is a consonant.", c);
return 0;
}
现在,如果用户输入一个非字母字符,您将看到
Enter an alphabet: 3 Error! Non-alphabetic character.