【发布时间】:2012-06-07 22:35:02
【问题描述】:
我正在做一个家庭作业,我在一个“for”循环中计算一个函数 (f(x) = x * x – 12 * x + 40) 的整数区间中的值。我需要找到一个最小值。没关系,但我还需要保留值最小的索引号。目前我在另一个循环中再次重申该功能,但这看起来真的很混乱。我也可以导出 x 并使用已知最小值计算答案,但这也很奇怪,因为推导不是那么简单。你对我有什么建议吗?谢谢。
#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;
}
【问题讨论】:
-
粘贴代码时请点击
{}按钮。 (发帖前请先看预览。)询问作业时请使用作业标签。 -
这个问题我们无法给出正确答案,因为这是家庭作业。这完全取决于导师的意图。也许您应该使用微积分来找到最小值。 (毕竟,根据多项式,它们可能不是唯一值或整数值。)也许您应该将事物存储在数组中。都有优点和缺点,这可能与作业无关。
-
所以你设法将最小值“y”保存在“min”中,但想不出将“i”保存到“minI”变量中的方法?
-
我理解需要保存相应最小值的“i”。我无法理解的是 min 只有在循环过去后才知道,因此所有“i”也都过去了......