问题描述
我正在用C ++编写我的第一个代码。 我想从用户那里收到N个号码,然后找到最大的一个。 我刚刚学会了烦躁,如果声明...(未列出) 请给我一些指导
解决方法
如果您想学习C ++,建议您直接开始使用标准库(stl),其容器(例如std::vector
)和算法(在这种情况下为std::max_element
)。
基于范围的循环不如适当的算法好,但仍优于基于索引的手工循环。
请参阅Stroustrup撰写的《 C ++之旅》一书。他总结了现在应该如何使用C ++。
代码如下:
#include <vector>
#include <limits>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> arr;
const int N = 10;
for (int i = 0; i<N; i++) {
int value;
std::cin >> value;
arr.push_back(value);
}
const auto max_algorithm = std::max_element(arr.begin(),arr.end());
std::cout << "Largest is: " << *max_algorithm << std::endl;
auto max_range_based_loop = std::numeric_limits<int>::lowest();
for (const auto& item : arr) {
max_range_based_loop = std::max(item,max_range_based_loop );
}
std::cout << "Largest is: " << max_range_based_loop << std::endl;
return 0;
}
,
初始化int max = INT_MIN。
在将用户输入放在数组中时,请检查每个输入元素是否大于max
,
如果更大,则更新最大值。
when循环终止时返回max
。
示例:
int main()
{
int N = 10; // N is array size
int arr[N]; // Array declaration
int max = INT_MIN;
for(int i=0; i<N; i++)
{
cin>>arr[i]; // user input
if(arr[i]>max) //check each element if it's greater than max
{
max = arr[i];
}
}
cout<<"Largest is: "<<max<<endl; // print max Or return it in a method
return 0;
}