C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C 检查字符是元音还是辅音的程序

检查字符是元音还是辅音的C程序

在本例中,您将学习检查用户输入的字母是元音还是辅音。
要理解此示例,您应该了解以下C 编程 主题:
C 编程运算符 C if...else 语句 C while 和 do...while 循环
五个字母 AEIOU称为元音。除这 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_voweluppercase_vowel 变量为 1(真),则输入的字符是元音。但是,如果 lowercase_voweluppercase_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.
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4