开关:一种情况下有多个值? [英] Switch: Multiple values in one case?

查看:66
本文介绍了开关:一种情况下有多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,但是当我输入"12"时,我仍然得到"You a old person". 9-15是9到15之前的数字吗?还有一种情况我该如何处理多个值?

I have the following piece of code, but yet when I enter "12" I still get "You an old person". Isn't 9 - 15 the numbers 9 UNTIL 15? How else do I handle multiple values with one case?

  int age = Convert.ToInt32(txtBoxAge.Text);

  switch (age) 

  {
    case 1 - 8:
  MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
    break;
    case 9 - 15:
  MessageBox.Show("You are only " + age + " years old\n That's too young!");
    break;
    case 16-100:
  MessageBox.Show("You are " + age + " years old\n Perfect.");
    break;
    default:
  MessageBox.Show("You an old person.");
    break;
  }

推荐答案

1-8 = -7

9-15 = -6

9 - 15 = -6

16-100 = -84

16 - 100 = -84

您有:

case -7:
    ...
    break;
case -6:
    ...
    break;
case -84:
    ...
    break;

可以使用:

case 1:
case 2: 
case 3:

etc,(也许更易读)使用:

etc, or (perhaps more readable) use:

if(age >= 1 && age <= 8) {
     ...
} else if (age >= 9 && age <= 15) {
     ...
} else if (age >= 16 && age <= 100) {
     ...
} else {
     ...
}

这篇关于开关:一种情况下有多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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