实验作业
1.输入课本各个例题,调试运行程序,并分析程序,将每一个程序改写2到3个版本,自己分析程序结果,然后再调试运行,核对分析结果的对错。
1.1
#include<iostream>
using namespace std;
int main()
{
cout<<"numerb of bytes in int is "<<sizeof(short int)<<endl;
cout<<"numerb of bytes in long int is "<<sizeof(float)<<endl;
cout<<"numerb of bytes in shott int is "<<sizeof(long double)<<endl;
cout<<"numerb of bytes in float is "<<sizeof(char)<<endl;
cout<<"numerb of bytes in double is "<<sizeof(double)<<endl;
cout<<"numerb of bytes in long double is "<<sizeof(long int)<<endl;
cout<<"numerb of bytes in char is "<<sizeof(short int)<<endl;
return 0;
}
1.2.1
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
bool flag=false;
cout<<flag<<endl;
cout<<boolalpha<<flag<<endl;
cout<<flag+7<<endl;
flag=0;
cout<<"执行语句flag=0;后flag的值为:"<<boolalpha<<flag<<endl;
flag=1.0;
cout<<"执行语句a=0.0;后flag的值为:"<<boolalpha<<flag<<endl;
cout <<noboolalpha<<flag <<endl;
return 0;
}
1.2.2
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
bool flag=false;
cout<<flag<<endl;
cout<<boolalpha<<flag<<endl;
cout<<flag+7<<endl;
flag=1;
cout<<"执行语句flag=0;后flag的值为:"<<boolalpha<<flag<<endl;
flag=0.0;
cout<<"执行语句a=0.0;后flag的值为:"<<boolalpha<<flag<<endl;
cout <<noboolalpha<<flag <<endl;
return 0;
}
//语句flag=1
分析:语句flag=1改变了最后的输出,成为true
/**********************************
****改成找到三个数中的最大值,并输出***
*************************************/
#include<iostream>
using namespace std;
int main()
{
int a=1,b=2,c=3;
if(a>b&&a>c)
cout<<"最大值是a="<<a<<endl;
else if(b>a&&b>c)
cout<<"最大值是b="<<b<<endl;
else
cout<<"最大值是c="<<c<<endl;
}
分析:要注意if-else语句的合理搭配!!
2.编写程序输入一个三角形的三条边,计算其面积和周长;
#include<iostream>
using namespace std;
#include<math.h>
void main()
{
float a,b,c;
cout<<"请输入边长a,b,c"<<endl;
cin>>a>>b>>c;
float p=(a+b+c)/2;
float s=p*(p-a)*(p-b)*(p-c);
if(sqrt(s)<=0)
cout<<"不存在这样的三角形,请重新输入"<<endl;
else
{
cout<<"周长是:"<<a+b+c<<endl;
cout<<"面积是:"<<sqrt(s)<<endl;
}
return;
}
分析:要满足两边之和大于第三边,所以要考虑不满足的情况,使用海伦公式,只需满足sqrt()>0即可,还要使用函数库<math.h>,否则发生错误!!
3.编写程序计算并输出课本本章习题3表达式的值并分析结果。
3.1
#include<iostream.h>
#include<math.h>
void main()
{
int e=1,f=4,g=2;
float m=10.5,n=4.0,k;
k=(e+f)/g+sqrt((double)n)*1.2/g+m;
cout<<k<<endl;
}
3.2
#include<iostream>
#include<math.h>
using namespace std;
void main()
{
float x=2.5,y=4.7;
float a=7;
float t;
t=x+a%3(int(x+y)%2)/4;
cout<<t;
}
4.编写一个程序,输入一个一元二次方程的三个系数,并计算其方程的解,然后输出。
#include<iostream.h>
#include<math.h>
double a,b,c;
void main()
{
cout<<"请输入方程的三个系数a,b,c:"<<endl;
cin>>a>>b>>c;
double x1,x2,x,t;
t=sqrt((b*b-4*a*c));
if(b*b-4*a*c>0)
{
x1=(-b+t)/(2*a);
x2=(-b-t)/(2*a);
cout<<"x1:"<<x1<<endl;
cout<<"x2:"<<x2<<endl;
}
else if(b*b-4*a*c==1)
cout<<"x:"<<(-b+t)/(2*a)<<endl;
else
cout<<"输入有误或不存在这样的一元二次方程"<<endl;
}
6.在一个自动控制设备中,控制字位数16位,控制设备产生机械动作(如削,压等)的是指令字的低8位,其中保护强制停机动作的控制命令是低8位是全为0,控制报警声音是指令的高第1位,0为报警,1为不报警。请编写程序,在紧急状况启动时,向控制器输入控制指令。
7.积累调试程序经验,收集错误信息原因(每个同学收集3-5条错误信息原因,并输入电脑形成文字
对于程序的要值得注意的地方和容易出错的地方已经在分析中之处