热门搜索 :
考研考公
您的当前位置:首页正文

实验一代码

来源:伴沃教育
第一题:

//exp1_1.cpp:输入2个数,求平均值 #include using namespace std; int main() { int a,b; double ave; cout<<\"Please enter a and b:\"<>a>>b; ave=(a+b)/2.0; cout<<'('<第二题: /*

关于下面范例程序的说明: 我的思路是:

a,b,c三个系数构成一元二次方程。

1)如果a=0;其实这已经不是一元二次方程了,可以输出“出错提示语句”,我的做法是,继续判断b;

1.1)如果b=0;那么方程变成了 c=0; 这是无解的

1.2)如果b≠0;那么方程变成 bX+c=0; 可求出一个根 如何处理 a=0的情况,可以自己决定 2)当a≠0,这个时候再来求 △的值

2.1)如果△>0;那么方程有2个不等实数根

2.2)如果△=0;那么方程有2个相等实数根 2.3)如果△<0;那么方程有2个虚数根 */

//exp1_2.cpp:求一元二次方程的根 #include #include using namespace std;

int main() { const double zero=1e-4; double a,b,c,delta; double rp,ip,x1,x2; cout<<\"Please enter a,b,c:\"<>a>>b>>c; if(fabs(a)<=zero)//如果a=0 { if(fabs(b)<=zero) cout<<\"方程无解\"<zero)//如果delta>0,有2个实根 { x1=(-b+sqrt(delta))/(2*a); x2=(-b-sqrt(delta))/(2*a); cout<<\"有两个实根:\"<第三题:

//exp1_3_for:用for循环实现求和 #include using namespace std; int main() { double s=0; for(int i=1;i<=1000;i++) { s=(i%2==0)?(s-1.0/i):(s+1.0/i); } cout<<\"s=\"<//exp1_3_while:用while循环实现求和 #include using namespace std; int main() { double s=0; int i=1; while(i<=1000) { if(i%2==0) s=s-1.0/i; else s=s+1.0/i; i++; } cout<<\"s=\"<//exp1_3_do:用do while循环实现求和 #include using namespace std; int main() { double s=0; int i=1; do

{ if(i%2==0) s=s-1.0/i; else s=s+1.0/i; i++; }while(i<=1000); cout<<\"s=\"<//exp1_3_2:修改上面代码,最后一项分母由键盘读入 #include using namespace std; int main() { double s=0; int n; cout<<\"Please enter n:\"<>n; for(int i=1;i<=n;i++) { if(i%2==0) s=s-1.0/i; else s=s+1.0/i; } cout<<\"s=\"<//exp1_3_3.cpp:在第一步程序上修改,以实现精度要求,最后一项绝对值小于1E-4时停止。 #include using namespace std; int main() { double s=0; int i=1; while((1.0/i)>=1e-4) { if(i%2==0) s=s-1.0/i;

else s=s+1.0/i; i++; } cout<<\"s=\"<第四题

//exp1_4.cpp:打印下三角九九乘法表 #include #include using namespace std; int main() {

int a,b;

for(a=1;a<=9;a++) {

for(b=1;b<=a;b++)

cout<return 0; }

//exp1_4_2.cpp:打印全部九九乘法表 #include #include using namespace std; int main() {

int a,b;

for(a=1;a<=9;a++) {

for(b=1;b<=9;b++)

cout<return 0; }

//exp1_4_3.cpp:打印上三角九九乘法表 #include #include using namespace std; int main() { int i,j,k; for(i=1;i<=9;i++) { for(k=1;k