Finding a minimum value in a for loop and keeping the index of it

可紊 提交于 2019-12-25 04:59:08

问题


I am working on a homework assignment where I calculate the values in an interval of integers of a function (f(x) = x * x – 12 * x + 40) in a 'for' loop. I need to find a minimum value. That's all fine, but I also need to keep the index number for which the value was smallest. At the moment I reiterate the function again in another loop, but this looks really messy. Also I could derive x and calculate the answer using the known minimum, but that's also weird, because derivation is not so straightforward. Do you have any tips for me? Thanks.

#include <iostream>
#include "limits.h"
using namespace std;

int main ()
{
    int lBound, uBound, y, min;

    cout << "Give the lower and the upper bounds of integer numbers: " << endl;
    cin >> lBound >> uBound;        

    min=INT_MAX;
    int x = lBound;
    for (int i = x; i <=uBound; i ++) {
        y = i * i - 12 * i + 40;
        cout << x << " " << y << endl;
        if (y<min) {
            min=y;
        }
        x++;            
    }
    for (int i = lBound; i <= uBound; i++) {
        y = lBound * lBound - 12 * lBound + 40;
        if (y==min) {
            y = lBound;
            i=uBound; // terminates the loop
        }
        lBound++;
    }               
    cout << "smallest value of the function is " << min << " for x = " <<  y << endl;                
    return 0;
}

回答1:


Here's a hint: Whenever you need to "keep something around" in a program, that means you need to store it in a variable. Whether that variable is local, global, or passed around depends on how long you need to keep it around. This is called the variable's "scope". It's considered good practice to keep the scope of any variable to a minimum, hence the guidelines discouraging globals.




回答2:


        i=uBound; // terminates the loop

This is not a very good coding practice. To terminate a loop, you should use a flow control construct like break. Doing so in this case would preserve the index of the minimum element.

Edit: If you want i to outlive the loop, you simply need to declare it outside. To wit:

change

for (int i = lBound; i <= uBound; i++) {

to

int i; // variable exists outside loop
for (i = lBound; i <= uBound; i++) {

Furthermore, just FYI, loop bounds are usually specified as half-open intervals to avoid the potential issue where lbound and ubound represent the limits of the int data type. This means that you usually use < instead of <=.

It's not clear if you're in an algebra class or a CS class…



来源:https://stackoverflow.com/questions/10871391/finding-a-minimum-value-in-a-for-loop-and-keeping-the-index-of-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!