在for循环中找到最小值并保持它的索引 [英] Finding a minimum value in a for loop and keeping the index of it

查看:242
本文介绍了在for循环中找到最小值并保持它的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个家庭作业,在一个函数的整数区间(f(x)= x * x - 12 * x + 40)中计算一个'for'循环中的值。我需要找到一个最小值。这一切都很好,但我也需要保持值最小的索引号。此刻我又在另一个循环中重申了这个函数,但是这看起来非常混乱。我也可以推导出x并使用已知的最小值计算答案,但这也很奇怪,因为推导并不那么简单。你有什么提示吗?谢谢。

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


推荐答案

需要在程序中保持一些东西,这意味着你需要把它存储在一个变量中。无论该变量是本地的,全局的还是传递的,都取决于你需要保留多久。这被称为变量的范围。将任何变量的范围保持在最低限度是一个很好的做法,因此这个指导方针不鼓励全局变量。

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.

这篇关于在for循环中找到最小值并保持它的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆