1. switch语句根据表达式取值不同,分别执行不同语句,格式为:
 1 switch  表达式
 2 case 表达式1
 3        语句组1
 4 case 表达式2
 5        语句组2
 6 case 表达式m
 7       语句组m
 8 otherwise
 9        语句组 n    
10 end

 

  1. 例:某商场对顾客购买的商品实行打折销售,标准如下(商品价格用price来表示):
    1. price<200  没有折扣
    2. 200<=price<500      %3折扣
    3. 500<=price<1000    %5折扣
    4. 1000<=price<2500  %8折扣
    5. 2500<=price<5000  %10折扣
    6. 5000<=price           %14折扣

输入所售商品价格,求其实际销售价格。

 1 price = input ('请输入价格');
 2 switch fix(price/100)
 3 case {0,1}    %价格小于200
 4     rate=0;
 5 case {234}    %价格大于200但小于500
 6     rate=3/100;
 7 case num2cell(5:9)    %价格大于500但小于1000
 8     rate=5/100;
 9 case num2cell(10:24)    %价格大于等于1000但小于2500
10     rate=8/100;
11 case num2cell(25:49)    %价格大于2500但小于5000
12     rate=10/100;
13 otherwise
14     rate=14/100;     
15     end
16 price=price*(1-rate)         %输出商品实际销售价格
17 
18 
19 %num2cell函数是将数值转化为单元矩阵,num2cell(5:9)等价于{56789}。

 

posted on 2014-09-22 22:51  奶味洋葱头  阅读(4951)  评论(0编辑  收藏  举报