gpt4 book ai didi

c++ - 获取 C++ double 函数以在满足特定条件时报告消息而不是返回数字

转载 作者:行者123 更新时间:2023-12-01 14:48:18 26 4
gpt4 key购买 nike

我对 C++ 很陌生,我正在尝试创建一对函数来报告二次方程的两个可能的实解。我还试图在这些函数中输入一条消息,如果不存在真正的解决方案,这些消息将代替解决方案显示。

函数正确报告实解,但是当出现非实解时,程序将返回“此问题的两个可能的实解是 nan 和 nan”,以及我的错误消息(“该二次方程没有真正的解. 请输入一组不同的数字”) 根本不显示在终端中。

这是我的代码。预先感谢您的帮助!

 #include <iostream>
#include "std_lib_facilities.h" // from a Github page by Bjarne Stroustrup that corresponds with the Programming: Practices and Principles book. Note that I am learning this on my own; it is not for homework.
#include <cmath>


double quafo1 (double a, double b, double c)
{

if ((sqrt((b*b)-(4*a*c))) < 0)
{
cout << ("There is no real solution to that quadratic equation. Please enter a different set of numbers;/n");

}
else {
double x1 = ((b * -1) + sqrt((b * b) - (4 * a * c))) / (2 * a);
return x1;
}

}

double quafo2 (double a, double b, double c)
{

if ((sqrt((b*b)-(4*a*c))) < 0)
cout << ("There is no solution to that quadratic equation. Please enter a different set of numbers;");

else {
double x2 = ((b * -1) - sqrt((b * b) - (4 * a * c))) / (2 * a);

return x2;
}


}

double a;
double b;
double c;
int main()
{
cout << "This program will solve a quadratic equation as long as one or more real solutions are possible. Please enter values for a, b, and c (separated by spaces and followed by enter, e.g. 3 5 4), after which both possible answers for x will be provided. Please note that a cannot equal 0.\n";
while (cin >> a >> b >> c)
{
cout << "The two possible real solutions to this problem are " << quafo1(a, b, c) << " and " << quafo2(a,b,c) << ".\n";

}
}

最佳答案

sqrt函数永远不会返回负值*,因此您的测试 (sqrt((b*b)-(4*a*c))) < 0永远不会是真的。您可能想要做的是测试 sqrt 的参数是否是否定的:

    if (((b*b)-(4*a*c))) < 0) {
cout << ("There is no solution to that quadratic equation. Please enter a different set of numbers;");
return nan("");
}
else {
//...

或者,如果该参数为负,则 sqrt函数将返回 NaN ,您可以使用 isnan() 进行测试功能:

    if (isnan(sqrt((b*b)-(4*a*c)))) {
cout << ("There is no solution to that quadratic equation. Please enter a different set of numbers;");
//...

随时要求进一步澄清和/或解释。

注意:严格来说,任何(正)数都有两个平方根,一正一负: 2 x 2 = 4还有 -2 x -2 = 4 .

关于c++ - 获取 C++ double 函数以在满足特定条件时报告消息而不是返回数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61004612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com