最少 10 个数字使用 for 循环

Minimum of 10 numbers using for loop

本文关键字:for 循环 数字 最少      更新时间:2023-10-16

我在这段代码中有一个简单的问题:

#include <iostream>
using namespace std;
int main () {
int x, mn = 10000;
for (int i = 0 ; i<10 ; i++)
{
cin>>x;
if (x<mn)
mn=x;
}
cout << mn;
return 0;
} 

如果我们认为用户不会输入大于 10000 的数字,为什么这会输出最小值,尽管如果情况为真?
如果输入是:在示例 1、2、3、4、5、6、7、8、9、10 中,我的逻辑是:

1<mn 
okay now mn =1; 
2<mn 
okay now mn =2; 
........ and so on, til mn = 10;

为什么它不输出 10(最后一个值)?
如果你帮忙,我将不胜感激。
PS:我还需要一个建议,以便更好地理解代码如何运行,作为初学者。

为什么它不输出 10(最后一个值)?

您对该程序的理解不正确。

你说:

1<mn 
okay now mn =1; 

这是正确的。

2<mn 
okay now mn =2; 

这是不正确的。此时,mn的值1。因此2 < mn是不正确的。如果您不更改mn的值而只是打印x,则确实如此。

for (int i = 0 ; i<10 ; i++)
{
cin>>x;
if (x<mn)
cout << x << endl;
}

我已经注释了代码以帮助您理解每一行。

#include <iostream>
using namespace std;
int main () {       // Start execution
int x, mn = 10000;  // Place a value of 10,000 into minimum - higher than the supposed maximum value that can be entered.  (This is not a good number to use)
for (int i = 0 ; i<10 ; i++)  // Loop 10 times
{
cin>>x;    // Input a value into x
if (x<mn)  // if x is less than mn (first loop it is 10,000) then...
mn=x;  // Assign x into mn.
}
cout << mn;    // Output mn.  If no minimum was entered or found, this prints 10000
return 0;      // return 0
}