2

作业“使用枚举器重写章节中的菜单选择器程序来表示难度级别。变量选择仍然是 int 类型。”

第一组代码是原始的未污染形式的原始菜单选择器程序。第二组代码是我为了完成任务而添加的。

我唯一想问的是:我是否正确地完成了我的作业。如果我做错了,有人可以解释我做错了什么。我对此很陌生。

代码集 #1 - 原始

#include <iostream>
using namespace std;
int main()
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";

int choice;
cout << "Choice: ";
cin >> choice;

switch (choice)
{
    case 1:
            cout << "You picked Easy.\n";
            break;
    case 2:
            cout << "You picked Normal.\n";
            break;
    case 3:
            cout << "You picked Hard.\n";
            break;
    default:
            cout << "You made an illegal choice.\n";
}

return 0;
}

代码集 #2 - 分配

#include <iostream>

using namespace std;

int main()
{
    cout << "Difficulty Levels\n\n";
    cout << "0 - Novice\n";
    cout << "1 - Easy\n";
    cout << "2 - Normal\n";
    cout << "3 - Hard\n";
    cout << "4 - Unbeatable\n\n";

enum {Novice = 0, Easy = 1, Normal = 2, Hard = 3, Unbeatable = 4};

int choice;
cout << "Choice: ";
cin >> choice;

switch (choice)
{
    case 0:     
            cout << "You have picked Novice.\n";
            break;
    case 1:
            cout << "You picked Easy.\n";
            break;
    case 2:
            cout << "You picked Normal.\n";
            break;
    case 3:
            cout << "You picked Hard.\n";
            break;
    case 4: 
            cout << "You picked Unbeatable.\n";
            break;
            default:
            cout << "You made an illegal choice.\n";
}

return 0;
}
4

1 回答 1

3

我会做这样的事情:

#include <iostream>
using namespace std;

int main()
{
    cout << "Difficulty Levels\n\n";
    cout << "0 - Novice\n";
    cout << "1 - Easy\n";
    cout << "2 - Normal\n";
    cout << "3 - Hard\n";
    cout << "4 - Unbeatable\n\n";

    enum {NOVICE = 0, EASY = 1, NORMAL = 2, HARD = 3, UNBEATABLE = 4};

    int choice;
    cout << "Choice: ";
    cin >> choice;

    switch (choice) {
        case NOVICE:     
            cout << "You have picked Novice.\n";
            break;
        case EASY:
            cout << "You picked Easy.\n";
            break;
        case NORMAL:
            cout << "You picked Normal.\n";
            break;
        case HARD:
            cout << "You picked Hard.\n";
            break;
        case UNBEATABLE: 
            cout << "You picked Unbeatable.\n";
            break;
        default:
            cout << "You made an illegal choice.\n";
            break;
    }  
    return 0;
}

这样你就表明你至少在使用你的枚举。

于 2013-09-13T08:06:58.047 回答