【问题标题】:Switch statement default range?switch 语句的默认范围?
【发布时间】:2016-02-24 03:10:03
【问题描述】:

这是我无法弄清楚的作业规范的最后一部分:

使用默认大小写来“捕捉”大范围的成绩。 不要将 0 到 59 的每个数字都单独列出!

这是我的代码,我的默认值需要使用上述说明考虑 0 到 59 之间的值。

感谢您的任何帮助/建议。

double percentage;
int grade;

cout << "Enter your grade percentage " <<endl;
cin >> percentage;

if (percentage < 0 || percentage > 100 )
    cout << "Invalid entry " << endl;

grade = (int)round(percentage);

cout << fixed << setprecision(2);

switch(grade)

{
    case 100:
    case 99:
    case 98:
    case 97:
    case 96:
    case 95:
    case 94:
    case 93:
    case 92:
    case 91:
    case 90:
        cout << "Percentage: " << percentage << "% " << "Grade: A " << "Points: 4.00"; 
        break;
    case 89:
    case 88:
    case 87:
    case 86:
    case 85:
    case 84:
    case 83:
    case 82:
    case 81:
    case 80:
        cout << "Percentage: " << percentage << "% " << "Grade: B " << "Points: 3.00";
        break;
    case 79:
    case 78:
    case 77:
    case 76:
    case 75:
    case 74:
    case 73:
    case 72:
    case 71:
    case 70:
        cout << "Percentage: " << percentage << "% " << "Grade: C " << "Points: 2.00";
        break;
    case 69:
    case 68:
    case 67:
    case 66:
    case 65:
    case 64:
    case 63:
    case 62:
    case 61:
    case 60:
        cout << "Percentage: " << percentage << "% " << "Grade: D " << "Points: 1.00";
        break;
    default:
        cout << "Percentage: " << percentage << "% " << "Grade: F " << "Points: 0.00";
        break;
}
return 0;

}

【问题讨论】:

  • 这显然是在 C++ 中
  • 您可以编辑您的问题,重新标记它们...更正格式方面的问题,或响应澄清请求。 (但不要编辑以使其成为一个新问题......问一个新问题......!)但更重要的是,你不知道什么?你给它什么输入,你得到什么让你困惑的输出?
  • 如果你在学校学过编程,你应该知道if statements are for ranges and switch statements are for conditions。反正我就是这么教的,不知道为什么你的老师会期望一个 switch 语句。
  • @ub3rst4r:嗯? if 语句用于条件 (if (condition) statement)。 switch 语句用于从一组值中进行选择。
  • 提示:一旦你将grade 标准化为[0, 100],想想grade / 10 可以取什么值,以及它们与grade 范围的关系。

标签: c++ switch-statement case default


【解决方案1】:

根据@dvix 的评论,如果您知道成绩将在 0 到 100 之间,您可以通过以下方式缩短代码:

switch( grade/10 ) {

    case 10:
    case 9:
        ... Do something ...
        break;
    case 8:
    case 7:
        ... Do something else...
        break
   ....

}

最后使用默认值,节省几个案例。

话虽如此,if 可能是正常处理此问题的惯用方式。

【讨论】:

    猜你喜欢
    • 2014-06-12
    • 2014-08-11
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多