使用嵌套循环查找最大值

时间:2014-05-13 15:07:21

标签: c++ loops max nested-loops

  

块引用

我试图通过从步长为Δ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;
}

1 个答案:

答案 0 :(得分:1)

从伪代码到实际代码的进展:


<强>伪码:

  • 最大值从负无穷大开始(以便每个数字更大)
  • X从A
  • 开始
  • 对于每个点X,(直到X在B处),将X移动delta-X
    • 评估f(x)。
    • 将f(x)与最大值进行比较:如果f(x)更大,则将该值存储在最大值
  • 继续循环
  • 显示结果。

<强>八九不离十-代码

{
    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
}

<强>实时代码

(你填写它...伪代码和分类代码有你需要的大部分内容)

真的,这应该足以让你感动。