fangcheng.cpp 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4. int main()
  5. {
  6. double a,b,c,a2,a21,b1,x1,x2,gdelta,delta1,mum,den,mum1,den1;
  7. int qu=1,delta,delta2;
  8. cout<<"请输入a、b、c"<<endl;
  9. cin>>a>>b>>c;//输入系数
  10. cout<<a<<"x^2+"<<b<<"x+"<<c<<"=0"<<endl;
  11. delta=delta1=(b*b)-(4*a*c);
  12. cout<<"delta="<<delta<<endl;
  13. if (delta>=0&&(b*b)-(4*a*c)==floor((b*b)-(4*a*c)))//判断Δ是否>=0以及是否是整数
  14. {
  15. gdelta=sqrt(delta);
  16. if (gdelta==floor(gdelta))//判断根号下Δ是否是整数
  17. {
  18. x1=(-b+gdelta)/(2*a);
  19. x2=(-b-gdelta)/(2*a);
  20. if (x1==floor(x1)&&x2==floor(x2))//判断解是不是整数
  21. {
  22. cout<<"x1="<<x1<<"\nx2="<<x2<<endl;
  23. }
  24. else
  25. {
  26. mum=-b+gdelta;
  27. den=2*a;
  28. for (int j = 2; j<=fabs(mum)&&j<=fabs(den); j++)
  29. {
  30. mum1=mum/j;
  31. den1=den/j;
  32. if (mum1==floor(mum1)&&den1==floor(den1))
  33. {
  34. mum=mum1;den=den1;
  35. j=j-1;
  36. }
  37. }
  38. cout<<"x1="<<mum<<"/"<<den<<endl;
  39. mum=-b-gdelta;
  40. den=2*a;
  41. for (int j = 2; j<=fabs(mum)&&j<=fabs(den); j++)
  42. {
  43. mum1=mum/j;
  44. den1=den/j;
  45. if (mum1==floor(mum1)&&den1==floor(den1))
  46. {
  47. mum=mum1;den=den1;
  48. j=j-1;
  49. }
  50. }
  51. cout<<"x2="<<mum<<"/"<<den<<endl;
  52. }
  53. }
  54. else
  55. {
  56. delta2=delta;
  57. for(int i=2;i<=delta;i++)
  58. {
  59. int cnt=0;
  60. while(delta!=i)
  61. {
  62. if(delta%i==0)
  63. {
  64. cnt++;
  65. delta=delta/i;
  66. delta2=delta2/i;
  67. }
  68. else break;
  69. }
  70. if(i==delta)
  71. {
  72. cnt++;
  73. delta=delta/i;
  74. delta2=delta2/i;
  75. }
  76. if(cnt!=0)
  77. {
  78. if (cnt%2==0)
  79. {
  80. qu=qu*pow(i,cnt/2);
  81. }
  82. if (cnt%2!=0)
  83. {
  84. qu=qu*pow(i,(cnt-1)/2);
  85. delta2=delta2*i;
  86. }
  87. }
  88. }//开根号
  89. a2=2*a;
  90. for (int j = 2; j<=fabs(a2)&&j<=fabs(b)&&j<=fabs(qu); j++)
  91. {
  92. a21=a2/j;
  93. b1=b/j;
  94. if (qu%j==0&&b1==floor(b1)&&a21==floor(a21))
  95. {
  96. qu=qu/j;a2=a21;b=b1;
  97. j=j-1;
  98. }
  99. }//化简
  100. cout<<"x1=("<<-b<<"+"<<qu<<"*sqrt("<<delta2<<"))/"<<a2<<"\nx2=("<<-b<<"-"<<qu<<"*sqrt("<<delta2<<"))/"<<a2<<endl;
  101. }
  102. }
  103. else if (delta>=0)
  104. {
  105. gdelta=sqrt(delta1);
  106. cout<<"delta="<<delta1<<endl;
  107. x1=(-b+gdelta)/(2*a);
  108. x2=(-b-gdelta)/(2*a);
  109. cout<<"x1="<<x1<<"\nx2="<<x2<<endl;
  110. }//如果Δ是小数的话,暴力求解(本人技术有限)
  111. else
  112. {
  113. cout<<"方程无实数根"<<endl;
  114. }
  115. system("pause");
  116. return 0;
  117. }