Is using decimal ranges in a switch impossible in C#?(在 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 switch
statement 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# 中是否不可能在开关中使用小数范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中是否不可能在开关中使用小数范围?
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01