检查一个字符是元音还是辅音的 C 程序
要理解此示例,您应该具备以下 C 语言编程主题的知识:
五个字母 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
(true
) ,否则为 0
(false
)。
同样,如果变量 c
是大写元音, uppercase_vowel
的结果为 1
(true
) ,否则为 0
(false
)。
只要 lowercase_vowel
和 uppercase_vowel
中的至少一个为 1
(true
),那么输入的字符是元音。否则,输入的字符是辅音。
**注意:**此程序假定用户将输入的是一个字母。如果用户输入非字母字符,则显示该字符是辅音。
为了解决这个问题,我们可以使用 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.