c++第4章习题讲解.docVIP

  • 1
  • 0
  • 约3.67千字
  • 约 5页
  • 2018-05-25 发布于河南
  • 举报
c第4章习题讲解

4-1 #include iostream using namespace std; int hcf(int,int); int lcd(int,int,int); int main() { int u,v,h,l; cinuv; h=hcf(u,v); coutu””v”的最大公约数为”hendl; l=lcd(u,v,h); coutu””v”的最小公倍约数为”lendl; return 0; } int hcf(int u,int v) { int t,r; if (vu) {t=u;u=v;v=t;} while ((r=u%v)!=0) { u=v; v=r; } return(v); } int lcd(int u,int v,int h) { return(u*v/h); } } 4-2 方案1:(不设全局变量,根的输出放在自定义函数中) #include iostream #include math.h using namespace std; int main() { void greater_than_zero(float,float,float ); void equal_to_zero(float,float,float); void smaller_than_zero(float,float,float); float a,b,c,disc; coutinput a,b,c:; cinabc; disc=b*b-4*a*c; coutroot:endl; if (disc0) greater_than_zero(a,b,disc); else if (disc==0) equal_to_zero(a,b,disc); else smaller_than_zero(a,b,disc); return 0; } void greater_than_zero(float a,float b,float disc ) /* 定义函数,用来求disc0时方程的根 */ { float x1,x2; x1=(-b+sqrt(disc))/(2*a); x2=(-b-sqrt(disc))/(2*a); coutx1=x1,x2=x2endl; } void equal_to_zero(float a,float b,float disc) /* 定义函数,用来求disc=0时方程的根 */ { float x1,x2; x1=x2=(-b)/(2*a); coutx1=x1,x2=x2endl; } void smaller_than_zero(float a,float b,float disc) /* 定义函数,用来求disc0时方程的根 */ { float p,q; p=-b/(2*a); q=sqrt(-disc)/(2*a); coutx1=p+qiendl; coutx2=p-qiendl; } 方案1:(全局变量,根的输出放在主函数中) #include iostream #include math.h using namespace std; float x1,x2,disc,p,q; int main() { void greater_than_zero(float,float); void equal_to_zero(float,float); void smaller_than_zero(float,float); float a,b,c; coutinput a,b,c:; cinabc; disc=b*b-4*a*c; coutroot:endl; if (disc0) { greater_than_zero(a,b); coutx1=x1,x2=x2endl; } else if (disc==0) { equal_to_zero(a,b); coutx1=x1,x2=x2endl; } else { smaller_than_zero(a,b); coutx1=p+qiendl; coutx2=p-qiendl; } return 0; } void greater_than_zero(float a,float b) /* 定义一个函数,用来求disc0时方程的根 */

文档评论(0)

1亿VIP精品文档

相关文档