如何打印枚举变量的内容?

来源:4-3 固定内容的容器:枚举

weixin_慕无忌7470481

2023-12-14 19:04

#include <stdio.h>

#include <string>

using namespace std;



struct Student

{

    int math;

    int english;

};

enum myclass {

    chinese,

    english,

    math,

    PE,

    art,

    computer,

};


int main(int argc, char** argv)

{

    struct Student s = { 95,35 };

    myclass my = myclass::math;

    printf("?");

    return 0;

}



写回答 关注

1回答

  • 永恒丿丶之火
    2024-01-07 23:07:27

    在编程中,枚举变量通常用于定义一组具有离散取值的常量。每个枚举常量都与一个整数值关联,这些整数值按照定义顺序从0开始递增。

    默认情况下,第一个枚举常量的关联值为0,后续的枚举常量的关联值依次递增。你也可以显式地为枚举常量指定特定的关联值。

    枚举变量的提出是为了方便对一组离散的值进行管理和表示,而为了正确的限定这组离散的值的范围,就规定了枚举变量和整数值相关联。


    一般来说,我们不会对枚举变量的值进行打印,而是根据其值进行一些逻辑判断,例如下面的代码:

    if (my == myclass::math) {

            printf("my class is math!");

            // 处理 my 为 match 的逻辑

    }


    如果想打印其值的话,直接把枚举变量看作一个整数进行打印即可:

    printf("The value of my is: %d\n", my);

    当 my 为 match 的时候,值应该为 2,因为是从 0 开始排序的:

    enum myclass {

        chinese,      // 0

        english,       // 1

        math,           // 2

        PE,               // 3

        art,               // 4

        computer,    // 5

    };

趣味 C++ 入门

C++ 入门,开启趣味学习之旅,揭开 C++ 的神秘面纱,让你不再望而生畏。

31184 学习 · 189 问题

查看课程

相似问题