武汉理工大学c语言实验及答案(共5页).doc
精选优质文档-倾情为你奉上实验二 选择结构的程序设计1编程计算下面的分段函数。 4x-8 -1x0 y= 3x2+10x-1 0x1 8x3-3x2+2x-1 1x2 (1)事先编好程序和流程图。要求用if语句结构实现,注意数据类型和输入提示语句。#include <stdio.h>main ( ) float x,y; printf ("input x:n"); scanf ("%f",&x); if (x>=-1&&x<2) if (x>=-1&&x<0) y=4*x-8; else if (x>=0&&x<1) y=3*x*x+10*x-1; else y=8*x*x*x-3*x*x+2*x-1; printf("y=%10.2f",y); else printf ("DATA ERROR!");(2)将程序运行六遍,分别从键盘上输入-1,-0.5,0,0.5,1,1.5这六个数,记录下运行结果并核对结果的正确性。键盘的输入分析结果运行结果调试说明键盘输入-1键盘输入-0.5键盘输入0键盘输入0.5键盘输入1键盘输入1.5(3)再将程序运行二遍,分别从键盘上输入-3.5和2二个数,记录下运行结果并核对结果的正确性。键盘的输入观察到的运行结果程序的错误之处和调试说明键盘输入-3.5键盘输入 2修改程序,使之能正确处理任何数据。当输入数据大于等于2或小于-1时,通知用户“Data Error”,程序结束。键盘的输入运行结果程序的错误之处和调试说明键盘输入-1.5键盘输入-1键盘输入0键盘输入1键盘输入2键盘输入2.54水果店有苹果,一级5.50元/kg,二级4.20元/kg,三级3.00元 /kg,四级2.50/kg,输入苹果的等级、数量以及顾客的付款数,显示出苹果的等级、数量、应付款数以及找给顾客的钱数。(1)事先编好程序,分别用if语句和用switch语句结构实现,要求程序能正确处理任何数据。当输入苹果的等级、数量以及顾客的付款数不合要求时,通知用户“Data Error”,程序结束。注意苹果等级、数量以及顾客付款数数据的类型和输入数据的提示语句。(2)将程序运行六遍,分别从键盘上输入六组数,记录运行步骤、过程和结果,并核对结果的正确性。键盘的输入预期结果运行结果调试说明输入1,3.5,20输入2,2.0,10输入3,3.5,11输入4,2.5,6.25输入5,3,7输入2,3.5,-10#include <stdio.h>main( ) float weight,money,paid; int rank; printf ("input rank, weight, money: n"); scanf ("%d", &rank); printf ("input weight:n"); scanf ("%f",&weight); printf ("input money:n"); scanf ("%f",&money); switch (rank) case 1: paid=5.5*weight; break; case 2: paid=4.2*weight; break; case 3: paid=3.0*weight; break; case 4: paid=2.5*weight; break; default: paid=0; if (weight<=0|money<=0|paid<=0|(money-paid)<0) printf("DATA ERROR!"); else printf ("the rank is %d!", rank); printf ("the weight is %10.1f!", weight); printf ("paid %10.2f yuan", paid); printf ("the change is %10.2f yuan", money-paid); 实验三 循环结构的程序设计1编程序计算1!+2!+3!+4!+5!(1) 分别用单层循环和双层循环编写此程序,作出流程图。单层循环#include <stdio.h>main() int sum=0,p=1; int n,i; printf("please input n:n"); scanf("%d",&n); printf("n is %dn",n); for(i=1;i<=n;i+) p=p*i; sum = sum + p; printf("The result is %d:n",sum);双层循环:#include <stdio.h>main() int sum=0,p; int n,i,j; printf("please input n:n"); scanf("%d",&n); printf("n is %dn",n); for(i=1;i<=n;i+) for(j=1,p=1;j<=i;j+) p=p*j; sum = sum + p; printf("The result is %d:n",sum);(2) 分析两种编程的差别。单层循环效率更高,计算量小。(3) 若计算,运行程序观察程序结果是否正确,若有错误如何修改。不正确,数据越界,将int sum=0,p=1;改为long sum=0,p=1;printf("The result is %d:n",sum);改为printf("The result is %ld:n",sum);(4) 若计算,运行程序观察程序结果是否正确,若有错误如何修改。不正确,数据越界,将int sum=0,p=1;改为unsigned long sum=0,p=1;printf("The result is %d:n",sum);改为printf("The result is %ld:n",sum);2编写程序并上机调试 电视大奖赛有20名评委给选手评分。评分规则是:去掉1个最高分,去掉1个最低分,其余18名评委的平均分选手的得分。设计评分程序。#include <stdio.h>#define NUM 20main() int smin=0,smax=0,score; float sum=0; printf("please input player's score:n"); scanf("%d",&score); smax=smin=score; for(i=1;i<NUM;i+) scanf("%d",&score); if (score>smax) smax=score; if (score<smin) smin=score; sum = sum + score; sum = sum smax smin; printf("The result is %6.2f:n",sum/(NUM-2);专心-专注-专业