C语言根据输入字符判断星期几

以下是一个使用C语言编写的程序,它可以根据用户输入的第一个字符判断星期几:

#include<stdio.h>

int main()
{
    char a, b;
    printf('Please input the first character: ');
    scanf(' %c', &a);  // 在%c前面加上空格,消除之前输入字符的换行符影响
    if (a == 'M')
        printf('Monday\n');
    else if (a == 'W')
        printf('Wednesday\n');
    else if (a == 'F')
        printf('Friday\n');
    else 
    {
        scanf(' %c', &b);  // 在%c前面加上空格,消除之前输入字符的换行符影响
        if (a == 'T' && b == 'u')
            printf('Tuesday\n');
        else if (a == 'T' && b == 'h')
            printf('Thursday\n');
        else if (a == 'S' && b == 'a')
            printf('Saturday\n');
        else if (a == 'S' && b == 'u')
            printf('Sunday\n');
        else
            printf('Illegal input!\n');
    }
    return 0;
}

代码解释:

  1. #include<stdio.h>: 引入标准输入输出库。
  2. int main(): 程序的主函数入口。
  3. char a, b;: 声明两个字符型变量 ab,用于存储用户输入的字符。
  4. printf('Please input the first character: ');: 提示用户输入第一个字符。
  5. scanf(' %c', &a);: 读取用户输入的第一个字符并存储到变量 a 中。
  6. if (a == 'M') ... else if ... else ...: 使用 if-else if-else 语句根据输入的字符判断星期几。
  7. printf('Monday\n');: 如果输入的字符是 'M',则输出 'Monday'。
  8. scanf(' %c', &b);: 如果第一个字符不是 'M'、'W' 或 'F',则读取第二个字符并存储到变量 b 中。
  9. if (a == 'T' && b == 'u') ... else if ... else ...: 使用嵌套的 if-else if-else 语句根据输入的两个字符判断星期几。
  10. printf('Illegal input!\n');: 如果输入的字符不符合任何条件,则输出 'Illegal input!'。

注意:

  • 在使用 scanf 函数读取字符时,%c 前面加一个空格可以避免读取到之前输入的换行符。
  • 字符常量需要使用单引号括起来,例如 'M'、'u' 等。
  • 在代码中使用 \n 表示换行。

希望这段代码和解释能够帮助您理解如何使用C语言根据输入字符判断星期几!


原文地址: https://www.cveoy.top/t/topic/Vbl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录