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