gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:36:22 31 4
gpt4 key购买 nike

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

#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/

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