切换值的范围 [英] Switch with range of values
问题描述
因此,我根据雇员为公司工作的年数确定雇员的基本工资。
So I am to determine the base salary for an employee based on an inputed number of years the employee has worked for the company.
我必须这样做开关结构,我给出的范围如下:
I have to do this using switch structures and I am given ranges as follows:
工作年数_ __ _基本工资
Number of years worked____Base Salary
0 – 5 $ 9,500
6 – 11 $12,700
12 – 17 $15,300
18 – 29 $22,600
>= 30 $26,800
那么,如果我不想对所有的数字?
So, how do I do ranges for the cases if I don't want to right case for all of the numbers?
这不是一个麻烦,这一个,但然后我必须找出佣金基于销售,有范围如$ 0 -3,999.99和$ 16,000-23,999.99。
It isn't too much of a hassle with this one, but then I have to figure out commission based on sales and that has ranges like $0-3,999.99 and $16,000-23,999.99.
推荐答案
所以对于第一部分,你只需要声明一个开关,路径。像这样:
So for part one, you just need to declare a switch where multiple cases follow one code path. Like this:
int baseSalary
switch (yearsWorked)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
baseSalary = 9500;
break;
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
baseSalary = 12700;
break;
... etc ...
}
第二部分,对于每一个数字的开关,在几千的范围内是相当不可行的,但有一点智能划分,它可以同样容易。如果你把2000除以1000,你得到2,如果你除以1000,你还得到2(剩余500)。使用这个,你可以生成一个switch语句:
For the second part, a switch for every single number in a range of thousands is pretty unfeasible, but with a bit of smart division, it can be made equally easy. If you divide 2000 by 1000, you get 2, and if you divide 2500 by 1000, you also get 2 (with remainder 500). Using this, you can generate a switch statement:
int sales = 2100;
int salesRange = sales / 1000; // (salesRange = 2)
int commission
switch (salesRange)
{
case 0: // $0-999 sales
case 1: // $1000-1999 sales
case 2: // $2000-2999 sales
case 3: // $3000-3999 sales
commission = <some number here>;
break;
... etc ...
}
所以,这假定必须使用开关是学校作业或类似作业的一部分。正如其他人提到的,你最好使用带有范围的if语句(例如 if(sales> = 0&&& sales< = 3999)
)比使用开关这种东西。
That being said, this assumes that "have to use a switch" is part of a school assignment or similar. As the other people have mentioned, you're better off using if statements with a range (e.g. if (sales >= 0 && sales <= 3999)
) than using a switch for this kind of thing.
这篇关于切换值的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!