实验一
(1)设计简单程序,分别计算下列表达式,式中变量由键盘输入,输出表达式的值。
<1> x+(a+b)/(c-d)
#include<iostream>
using namespace std;
int main()
{
float x,a,b,c,d,y;
cin>>x>>a>>b>>c>>d;
y=x+(a+b)/(c-d);
cout<<"y="<<y<<endl;
return 0;
}
<2> y= √{1+1/[x+1/(1+x)]}
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float x;
float y =0;
float z=0;
float w=0;
float Y=0;
float y1=0;
cin>>x;
y=x+1;
z=1/y;
w=1/(x+z);
Y=1+w;
y1=sqrt(Y) ;
cout<<"y1="<<y1<<endl;
return 0;
}
<3> sinX+cosX+tan-1X
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float x,y;
cin>>x;
y=sin(x*3.1415926/180)+cos(x*3.1415926/180)+1/tan(x*3.1415926/180);
cout<<y<<endl;
return 0;
}
<4> ex+y+ex-y
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float x,y,z;
cin>>x>>y;
z=exp(x+y)+exp(x-y);
cout<<z<<endl;
return 0;
}
<5> log10(1+√(1+x*x))
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float x,y;
cin>>x;
y=log10(1+sqrt(1+x*x));
cout<<y<<endl;
return 0;
}
<6> |a^2-b^2|+[a-b]
(其中[a]表示取不大于a的最大整数)。
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a,b,c;
cin>>a>>b;
c=fabs(a*a-b*b)+floor(a-b);
cout<<c<<endl;
return 0;
}
(2)阅读下列程序,写出(由指定的输入)所产生的运行结果,并指出其功能。
<1>
#include <iostream.h>
void main()
{
char ch;
cin >> ch ;
ch = ( ch >= ’A’ && ch <= ’Z’ ) ? ( ch + 32 ) : ch ;
ch = ( ch >= ’a’ && ch <= ’z’ ) ? ( ch – 32 ) : ch ;
cout << ch << endl;
}
将输入的大写字母变为小写字母,小写字母变为大写字母
<2>
#include <iostream.h>
void main()
{
int m;
float x;
bool bi,br;
cout << "\n int m=";
cin >> m;
bi = m > 1000;
cout << "\n float x=";
cin >> x;
br = x <= 1e3;
cout << bi << ',' << br << endl;
}
分别输入100 40,2000 3000,1000 1000,2000 300,100 4000运行。
判断输入的数字a,b是否分别大于1000,和小于1000
<3>
#include <iostream.h>
void main()
{
int n;
cin >> n ;
if ( n ++ < 10 )
cout << n << endl ;
else
cout << n -- << endl ;
}
(3)编写程序实现下列问题的求解。
<1> 根据随机从键盘输入的圆半径值,求圆的周长和面积并输出。
#include<iostream>
using namespace std;
int main()
{ const float pi=3.1415926;
float r,c,s;
cout<<"请输入圆半径r:";
cin>>r;
c=2*pi*r;
s=pi*r*r;
cout<<"圆周长和面积分别为:"<<c<<" "<<s<<endl;
return 0;
}
<2> 读入三个整数a、b、c,交换它们中的数,使a存放b的值,b存放c的值,c存放a的值。
#include<iostream>
using namespace std;
int main()
{
int a,b,c,temp=0;
cout<<"请输入3个整数:";
cin>>a>>b>>c;
temp=a;
a=b;
b=c;
c=temp;
cout<<"交换的结果为:"<<endl;
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
return 0;
}
<3> 对任意输入的四位整数,分别求出其各位数字,并按从后到前的顺序依次输出。例如,输入为1234时,输出结果为4,3,2,1。
#include<iostream>
using namespace std;
int main()
{
int x,y,z,w,o;
cout<<"请输入一个四位数:";
cin>>x;
y=x/1000;
z=(x-y*1000)/100;
w=(x-y*1000-z*100)/10;
o=x-y*1000-z*100-w*10;
cout<<o<<endl;
cout<<w<<endl;
cout<<z<<endl;
cout<<y<<endl;
return 0;
}
3.思考题
* 对任意输入的小于1的并且只有3位尾数的实数,分别求出其各位数字并输出。要求输出的各数字之间要空2格。例如,输入为0.368时,输出结果为‘0 3 6 8’。
#include<iostream>
int main()
{
using namespace std;
float x;
int a,b,c,d;
cout<<"请输入一个大于0小于1的且小数点后有三位数字的小数:";
cin>>x;
a=x;
b=x*10;
c=x*100-b*10;
d=x*1000-b*100-c*10;
cout<<a<<" "<<b<<" "<<c<<" "<<d<<endl;
return 0;
}