c++ - 二次公式 c++ - 用户定义的函数

标签 c++ user-defined-functions

我用用户定义的函数编写了这段代码,但它似乎不起作用。我试图找出几个小时的错误所在。但是找不到任何东西。看起来问题在于传递参数。但我不知道,我对此很陌生!

#include <iostream>
#include <cmath>
using namespace std;

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

  double  delta, solution1, solution2;

  delta = b*b - 4*a*c;

  if (delta > 0 ){
    solution1 = (-b + sqrt(delta)) / (2*a);
    solution2 = (-b - sqrt(delta)) / (2*a);

    cout << "There are 2 solutions." << endl;
    cout << "The solutions are:";
    return solution1, solution2;
  }

  else if (delta == 0){
    solution1 = (-b) / (2*a);
    cout << "There is 1 solution." << endl;
    cout << "The solution is:";
    return solution1;
  }

  else {
    cout << "There is no solution.";
    return 0;
  }

}

int main(){

  double a ,b ,c;

  cout << "Please enter the values of a, b, and c respectively:";
  cin >> a ,b ,c;

  solutionFun(a ,b ,c);

  return 0;
}         

最佳答案

关于代码有效性和期望行为的一些问题(除了编码实践/设计):

  1. 了解如何从 solutionFun() 返回多个值(当前定义为返回 double )通过使用 std::vector -- 即使您没有使用这段代码中返回的任何内容。
  2. 您没有打印 ( cout << ) 解决方案本身的值(value),看起来您正在努力。
  3. 查看如何使用 std::cin在一行代码中进行多个输入。

固定版本——关于以上几点:

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

std::vector<double> solutionFun (double a, double b, double c) {

  double  delta, solution1, solution2;

  delta = b*b - 4*a*c;

  if (delta > 0 ){
    solution1 = (-b + sqrt(delta)) / (2*a);
    solution2 = (-b - sqrt(delta)) / (2*a);

    cout << "There are 2 solutions." << endl;
    cout << "The solutions are: " << solution1 << " and " << solution2;
    return {solution1, solution2};
  }

  else if (delta == 0){
    solution1 = (-b) / (2*a);
    cout << "There is 1 solution." << endl;
    cout << "The solution is: " << solution1;
    return {solution1};
  }

  else {
    cout << "There is no solution.";
    return {};
  }    
}

int main(){

  double a ,b ,c;

  cout << "Please enter the values of a, b, and c respectively:";
  cin >> a >> b >> c;

  auto result = solutionFun(a ,b ,c);

  for (auto scalar : result)
  {
    // Do something with a component, or don't return anything from the function : )
  }

  return 0;
}

关于c++ - 二次公式 c++ - 用户定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52300156/

相关文章:

c++ - 如何访问由 udev 在 opencv 中链接的网络摄像头

C++ lambda 不推断函数重载

c++ - 将非常量传递给常量 - *(new foo()) 和 foo() 作为参数传递时的区别

MySQL用户自定义函数生成主键

mysql存储函数返回值charset

hibernate - 如何在 PostgreSQL 的文字字符串中使用 '

c++ - 类类型非类型模板参数初始化不编译

mysql - MySQL udf创建报错1127

python - 从 Pyspark UDF 调用另一个自定义 Python 函数

c++ - 意外行为字符串文字