我知道有很多关于这个问题的主题,但这些都没有帮助我.我试图通过测试-10到10范围内的每个数字以及两个小数位来找到函数的根.我知道这可能不是最好的方式,但我是初学者,只是想尝试一下.不知怎的,循环不起作用,因为我总是得到-10作为输出.无论如何,这是我的代码:
#include <iostream>
using namespace std;
double calc (double m,double n)
{
double x;
for (x=-10;x<10 && m*x+n==0; x+=0.01)
{
cout << x << endl;
}
return x;
}
int main()
{
double m, n, x;
cout << "......\n";
cin >> m; // gradient
cout << "........\n";
cin >> n; // y-intercept
x=calc(m,n); // using function to calculate
cout << ".......... " << x<< endl; //output solution
cout << "..............\n"; // Nothing of importance
return 0;
}
Run Code Online (Sandbox Code Playgroud)