我用用户定义的函数编写了这段代码,但它似乎不起作用。我试图找出几个小时的错误所在。但是找不到任何东西。看起来问题在于传递参数。但我不知道,我对此很陌生!
#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;
}
最佳答案
关于代码有效性和期望行为的一些问题(除了编码实践/设计):
- 了解如何从
solutionFun()
返回多个值(当前定义为返回double
)通过使用std::vector
-- 即使您没有使用这段代码中返回的任何内容。 - 您没有打印 (
cout <<
) 解决方案本身的值(value),看起来您正在努力。 - 查看如何使用
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/