五个字母
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() 函数。
islapha()
函数检查字符是否为字母表。
#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.