CS106L 02 Code

118 阅读1分钟

CS106L 02 Code

要求去解决一个一元二次方程问题

首先用using关键词对零点是否存在解做了定义

using Zeros = std::pair<double, double>;
using Solution = std::pair<bool, Zeros>;

根据求根公式判断 b24acb^2 - 4 ac 与 0 关系来判断是否有解来解一元二次方程

Solution solveQuadratic(double a, double b, double c)
{
  double discrim = b * b - 4 * a * c;
  if (discrim < 0) return { false, { 106, 250 }};
  discrim = sqrt(discrim);
  return { true, { (-b - discrim) / (2 * a), (-b + discrim) / (2 * a) }};
}

再看输入输出,写的极其优美,简洁

  double a, b, c;
  std::cout << "a: "; std::cin >> a;
  std::cout << "b: "; std::cin >> b;
  std::cout << "c: "; std::cin >> c;

使用auto关键词来infer 变量

auto result = solveQuadratic(a, b, c);
  if (result.first) {
    auto solutions = result.second;
    std::cout << "Solutions: " << solutions.first << ", " << solutions.second << std::endl;
  } else {
    std::cout << "No solutions" << std::endl;
  }

整体代码如下, 代码为公开,不为assign,可以公开使用,符合课程规定:

#include <iostream>
#include <cmath>
#include <utility>

using Zeros = std::pair<double, double>;
using Solution = std::pair<bool, Zeros>;

/**
 * Solves the equation ax^2 + bx + c = 0
 * @param a The coefficient of x^2
 * @param b The coefficient of x
 * @param c The constant term
 * @return A pair. The first element (bool) indicates if the equation has a solution.
 *                 The second element is a pair of the roots if they exist.
 */
Solution solveQuadratic(double a, double b, double c)
{
  double discrim = b * b - 4 * a * c;
  if (discrim < 0) return { false, { 106, 250 }};
  discrim = sqrt(discrim);
  return { true, { (-b - discrim) / (2 * a), (-b + discrim) / (2 * a) }};
}

int main() {
  // Get the values for a, b, and c from the user
  double a, b, c;
  std::cout << "a: "; std::cin >> a;
  std::cout << "b: "; std::cin >> b;
  std::cout << "c: "; std::cin >> c;

  // Solve the quadratic equation, using our quadratic function above
  auto result = solveQuadratic(a, b, c);
  if (result.first) {
    auto solutions = result.second;
    std::cout << "Solutions: " << solutions.first << ", " << solutions.second << std::endl;
  } else {
    std::cout << "No solutions" << std::endl;
  }

  return 0;
}

End...