C++练习题2:求方程ax2+bx+c=0的根
// stdycpp02.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//求方程ax2+bx+c=0的根
/*方法1:用if判断求解方程的解;
*/
1 #include <iostream> 2 #include<cmath> 3 using namespace std; 4 5 void func_x2() { 6 double a, b, c, d, x1, x2; 7 cout << "求方程ax2+bx+c=0的根" << endl; 8 cout << "请输入一元二次方程a,b,c对应的值:" << endl; 9 cin >> a >> b >> c; 10 cout << "a=" << a << ",b=" << b << ",c=" << c << endl; 11 if (a == 0 && b == 0) { 12 cout << "方程无解" << endl; 13 return ; 14 } 15 if (a == 0) { 16 cout << "x的值是" << -c / b << endl; 17 return ; 18 } 19 d = b * b - 4 * a * c; 20 if (d < 0) 21 { 22 cout << "方程无解" << endl; 23 return ; 24 } 25 if (d == 0) { 26 x1 = (-b) / (2 * a); 27 cout << "x1=x2=" << x1 << endl; 28 return ; 29 } 30 if (d > 0) { 31 x1 = (-b + sqrt(d)) / (2 * a); 32 x2 = (-b - sqrt(d)) / (2 * a); 33 cout << "x1=" << x1 << ",x2=" << x2 << endl; 34 return ; 35 } 36 } 37 38 int main() 39 { 40 41 func_x2(); 42 43 // std::cout << "Hello World!\n"; 44 }

浙公网安备 33010602011771号