编程求解一元二次方程:请你编写一个程序,使其能求出多个二次方程的根。该程序要询问用户是否想继续解下一个方程。用户输入1来继续,输入其它数字,则终止程序。程序要求用户输入a,b和c
一元二次方程的定义为:ax^2+bx+c=0
显然最开始要对它进行一个判断是否存在实根,写一个函数,用一个if便可轻易实现:if ((b*b - 4 * a*c) >= 0)
如果成立输出两个实根即可,根号的符号为sqrt()>>两个实根分别为:(((-b) + (sqrt(b*b - 4 * a*c))) / (2 * a)),(((-b) - (sqrt(b*b - 4 * a*c))) / (2 * a))
如果不成立直接cout<<"错误"<<endl;就好
接下来,要求用户多次输入数据(如果为1的话)及需要写一个递归,在函数里再加上一个if进行判断用户最后输入的数是否为1即可,如果为1:就让用户接着输入数据,并调用这个函数自身进行实根判断,输出,如此循环便可达到题目要求。
直接上代码:
#include "pch.h"
#include <iostream>
using namespace std;
void funA(double a, double b, double c, int d)
{
if ((b*b - 4 * a*c) >= 0)
cout<<"结果为:" << (((-b) + (sqrt(b*b - 4 * a*c))) / (2 * a)) << " " << (((-b) - (sqrt(b*b - 4 * a*c))) / (2 * a)) << endl;
else
cout << "错误" << endl;
if (d == 1)
{
cout << "please cin four number:" << endl,
cin >> a >> b >> c >> d,
cout<<"结果为:",
funA(a, b, c, d),
cout << endl;
}
else cout << "surprise motherfuck!" << endl;
}
int main()
{
double a, b, c;
int d;
cout << "please cin four number as‘double, double, double, int’:" << endl;
cin >> a >> b >> c >> d;
funA(a, b, c, d);
cout << endl;
return 0;
}