在 C# 中是否不可能在开关中使用小数范围? [英] Is using decimal ranges in a switch impossible in C#?

查看:32
本文介绍了在 C# 中是否不可能在开关中使用小数范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习 C#,但我已经陷入了一些非常基础的问题.

I'm just starting out learning C# and I've become stuck at something very basic.

对于我的第一个应用程序",我想我会选择一些简单的东西,所以我决定使用 BMI 计算器.

For my first "app" I thought I'd go for something simple, so I decided for a BMI calculator.

BMI 被计算为十进制类型,我现在尝试在 switch 语句中使用它,但显然十进制不能在 switch 中使用?

The BMI is calculated into a decimal type which I'm now trying to use in a switch statement, but aparently decimal can't be used in a switch?

C# 解决方案是什么:

What would be the C# solution for this:

            decimal bmi = calculate_bmi(h, w);

            switch (bmi) {
                case < 18.5: 
                    bmi_description = "underweight.";
                    break;
                case > 25:
                    bmi_description = "overweight";
                case > 30:
                    bmi_description = "very overweight";
                case > 40:
                    bmi_description = "extreme overweight";
                    break;
            }

推荐答案

switch语句只支持整数类型(枚举未列出,但可以与 switch 语句一起使用,因为它们由整数类型支持)(字符串也支持为Changeling 指出 - 请参阅评论以供参考)以及与常量值的相等比较.因此,您必须使用一些 if 语句.

The switchstatement only supports integral types (enumerations are not listed but can be used with switch statements because they are backed by an integral type)(strings are also supported as pointed out by Changeling - see the comment for reference) and equality comparisons with constant values. Therefore you have to use some if statements.

if (bmi < 18.5M)
{
    bmi_description = "underweight.";
}
else if (bmi <= 25)
{
    // You missed the 'normal' case in your example.
}
else if (bmi <= 30)
{
    bmi_description = "overweight";
}
else if (bmi <= 40)
{
    bmi_description = "very overweight";
}
else
{
    bmi_description = "extreme overweight";
}

顺便说一句,您的 switch 语句有点奇怪,因为您正在从小于切换到大于并且使用不中断的直通.我认为应该只使用一种比较来使代码更易于理解或重新排序检查,并且不要使用失败.

By the way your switch statement is a bit weired because you are switching from less than to greater than and using fall-through without breaks. I think one should use only one type of comparison to make the code easier to understand or reorder the checks and do not use fall-through.

if (bmi < 18.5M)
{
    bmi_description = "underweight.";
}
else if (bmi > 40)
{
    bmi_description = "extreme overweight";
}
else if (bmi > 30)
{
    bmi_description = "very overweight";
}
else if (bmi > 25)
{
    bmi_description = "overweight";
}
else
{
    // You missed the 'normal' case in your example.
}

这篇关于在 C# 中是否不可能在开关中使用小数范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆