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# 中是否不可能在开关中使用小数范围?
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01