块引用
我试图通过从步长为Δx的x = a开始,在a< = x< = b的区间内找到函数f(x)的最大值。我想评估f1 = f(x)和f2 = f(x +Δx。如果f1 我的程序中有些东西不对,我认为这与输入等式的用户有关,但我不知道如何解决它。有什么建议?
这是我到目前为止编写的代码。#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int a, b, delta, fx, x, y;
int max = 0;
cout <<"Please complete the equation to be evluated f(x)= " << endl;
cin >> fx;
cout <<"Please enter the first number of the interval to be checked: " << endl;
cin >> a;
cout << "Please enter the last number of the interval to be checked: " << endl;
cin >> b;
cout << "Please enter the desired initial step size: " << endl;
cin >> delta;
for(x = a; x <= b; x = x+delta)
{
y = fx;
if (y > max)
{
max = y;
cout <<"The maximum over the interval from " << a <<"to " << b <<"is " << delta;
}
else
{
delta= delta/2;
}
if (delta < pow( 10, -6))
{system ("PAUSE");}
}
return 0;
}
答案 0 :(得分:1)
从伪代码到实际代码的进展:
<强>伪码:强>
<强>八九不离十-代码强>:
{
int max = INT_MIN; // Maximum starts at Negative Infinity (or as close as I can get)
for(x = a; x <= b; x = x+delta) // X starts at A
// for Every Point X (until B)
// move X by Delta.
{
y = f(x); // Evaluate f(x)
if (y > max) // Compare f(x) against Maximum)
{
max = y; // if f(x) is bigger, store that value
}
} // Continue Loop
}
<强>实时代码强>
(你填写它...伪代码和分类代码有你需要的大部分内容)
真的,这应该足以让你感动。