如何修复C++编写的一元二次方程求根求解器运行输出nan的问题
问题根因
你遇到的nan输出是两个边界场景未做校验导致的:
- 当判别式
b² - 4ac < 0时,你直接对负数调用sqrt()求平方根,C++的cmath库对负数入参的sqrt()调用会返回nan(非数值),这是nan最常见的触发原因 - 当二次项系数
a == 0时,分母2*a为0,除零操作也会返回nan或者无穷大值,且此时方程已经退化为一元一次方程,不能用二次求根公式计算
修复后的可运行代码
#include <iostream> #include <cmath> using namespace std; int main() { double a,b,c,discriminant,n,z,x1,x2,r; cout<<"Quadratic Equation Calculator"<<endl<<endl; cout<<"What is your 'a' value?: "<<endl; cin>>a; cout<<"What is your 'b' value?: "<<endl; cin>>b; cout<<"What is your 'c' value?: "<<endl; cin>>c; // 先处理a为0的一元一次方程场景 if (a == 0) { if (b == 0) { if (c == 0) { cout << "方程对所有实数成立" << endl; } else { cout << "方程无解" << endl; } } else { cout << "一元一次方程解为: x = " << (-c / b) << endl; } return 0; } // 计算判别式 discriminant = b*b - 4*a*c; if (discriminant > 0) { // 两个不同实根 n = -b; z = sqrt(discriminant); r = 2*a; x1 = (n + z)/r; x2 = (n - z)/r; cout<<"方程的解为: "<< x1 << " 或 "<< x2 << endl; } else if (discriminant == 0) { // 重根 x1 = (-b) / (2*a); cout<<"方程的解为(重根): "<< x1 << endl; } else { // 虚根场景,如果你不需要支持虚数可以直接输出无实根提示 double realPart = (-b) / (2*a); double imaginaryPart = sqrt(-discriminant) / (2*a); cout<<"方程的复数解为: "<< realPart << " + " << imaginaryPart << "i 或 " << realPart << " - " << imaginaryPart << "i" << endl; } return 0; }
内容的提问来源于stack exchange,提问作者Shane Douglas
相关产品推荐
相关产品推荐

