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

标签 c++ function

我对 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/

相关文章:

c++ - 静态库的 undefined reference 和奇怪的内容

c# - 类中的属性/方法占用内存空间吗?

c - 为什么编译器警告并忽略对我的函数 strlen 的调用?

带有 For 循环的 Python 定义函数

javascript - 使用 Emscripten 将 C++ ImpulseEngine 编译成 JavaScript

c++ - 使用 std::shared_ptr 时出现 malloc 错误

c++ - block 的某些线程到达 __syncthreads() 而其中一些不到达是否重要?

c++ - 为什么指向 vector 中变量的指针保持有效?

Matlab:如何合法关闭程序?

swift - 在函数中使用时类内存未释放