实验3 M文件及程序设计实验.docVIP

  • 33
  • 0
  • 约2.69千字
  • 约 5页
  • 2018-01-04 发布于河南
  • 举报
实验3 M文件及程序设计实验

实验 M文件及程序设计实验 一、实验目的 1. 掌握M文件与M函数的编写与应用; 2. 掌握if语句、switch语句的使用; 3. 掌握利用for语句、while语句实现循环结构的方法 二、实验内容 1.创建一个函数文件, 建立如下函数 x,y由键盘赋值,采用调用方法计算f值,试编写程序(M文件),并以x=6,y= -3及x=6,y=3二种情况运行,写出运行结果。x=input(input x=); y=input(input y=); if x+y=0 fun=x^2+y^2 else fun=x^2-y^2 end numb1 input x=6 input y=-3 fun = 45 numb1 input x=-6 input y=3 fun =27 2. 已知一元函数,编写程序求function y=y(x) y=3*x^3+2*x^2+x+20; end y(1)+y(2)^2+y(3)^3 ans = 1818790 3. 已知,计算f(-1),f(0.5),f(1.5)的值function f=f(x) if x=-2x0 f=x+1; elseif x=0x1 f=x^2+2; elseif x=1x=2 f=x^3+3; end f(-1) ans = 0 f(0.5) ans = 2.2500 f(1.5) ans = 6.3750 4. 分别用for循环语句、while循环语句求100! 和clear result=1; for i=1:100 result=result*i; end result exp result = 9.3326e+157 clear result=0; for i=1:100 result=result+i; end result exp result = 5050 clear result=1;i=0; while i100 i=i+1; result=result*i; end result exp result = 9.3326e+157 clear result=0;i=0; while i100 i=i+1; result=result+i; end result exp result = 5050 5. 若一个三位整数的各位数字的立方和等于该数本身,则称该整数为水仙花数,例如,153就是个水仙花数,编程序计算出所有的水仙花数。clear sum=0; for i=100:999 g=mod(i,10); s=(mod(i,100)-g)/10; b=(i-mod(i,100))/100; sum=g^3+s^3+b^3; if(i==sum) i end end shuixian i =153 i =370 i =371 i =407 6. 某商场对顾客所购买的商品实行打折销售,标准如下(商品价格用price来表示): price200 没有折扣 200≤price500 3%折扣 500≤price1000 5%折扣 1000≤price500 10%折扣 500≤price 20%折扣 任意输入某出售商品的价格,求其实际销售价格。 要求:(1)用switch语句实现。 (2)输入price后要判断该,对不合理的价格应输出出错信息。clear p=input(please input price ); if p0 disp(error price) z=0; elseif p200 z=1; elseif p=200p500 z=0.03; elseif p=500p1000 z=0.05; elseif p=1000p3500 z=0.10; else z=0.2; end switch(z) case 1 disp(no discount ) tp*z case 0.03 disp(3% discount) p*(1-z) case 0.05 disp(5% discount) p*(1-z) case 0.1 dis

文档评论(0)

1亿VIP精品文档

相关文档