最少 10 个数字使用 for 循环
Minimum of 10 numbers using for loop
我在这段代码中有一个简单的问题:
#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
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式