嵌套循环找到最大值

时间:2014-05-14 01:51:07

标签: c++ nested max

我正在编写程序,以便在用户给出的间隔内找到最大的方程式。当我编译代码而不是输出最大值时,它给了我这个

请输入要检查的间隔的第一个数字: 请输入要检查的间隔的最后一个数字: 请输入所需的初始步长: sh:PAUSE:找不到命令

我认为问题与我的循环有关,但我不确定如何纠正这种情况。 这是我的代码

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int a, b, delta, x, y;
    int max = 0;


    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 = pow(x, 2)-7*x-18;
        if (y > max)
        {
            max = y;
            cout <<"The maximum over the interval from " << a <<" to " << b <<" is " << max;
        }
        else
        {
            delta= delta/2;
        }
        if (delta <  pow( 10, -6))
        {
            break;
        }
    }      

    return 0;
}

1 个答案:

答案 0 :(得分:0)

看看你的代码,似乎delta的值应该是float,因为你递归地除以2.你的pow(10,-2)没有做任何有用的比较。即使在所有事情之后,它也没有给我带来暂停错误。我在VS 12(C ++ 11)上运行它。