如何解决我如何才能在循环中找到最大值?
我正在努力寻找公寓大楼的最大利润。我使用循环来查找所有不同的利润,但是我需要找到利润的最大值。 我如何才能找到最大利润? 我应该使用循环还是其他方式执行此操作? 我还是编码新手,非常感谢您的帮助。
#include <iostream>
using namespace std;
int main()
{
// Containers for all variables
int units;
int rent;
int incrent;
int maintain;
int profit;
// User input
cout << "How many units are being rented: ";
cin >> units;
cout << "How much is rent for each occupied room: $";
cin >> rent;
cout << "How much will rent need to increase for someone to leave: $";
cin >> incrent;
cout << "How much money does it cost to maintain a occupied room: $";
cin >> maintain;
//cout << "At max units rented you make $" << units * rent - maintain << endl;
//Profit calculations
while(units >= 0)
{
cout << "While at " << units << " rented you make $" << (units * rent) - (maintain * units) << endl;
rent = rent + incrent;
units--;
}
解决方法
自制的for循环的替代方法是使用std::max_element
,例如:
#include <iostream>
#include <algorithm>
int main() {
int arr[] = { 4,1,2,5,7 };
std::cout << *std::max_element(arr,arr + 5) << std::endl;
return 0;
}
,
您可以在下面的代码中使用逻辑来解决您的问题,希望对您有所帮助。
#include <iostream>
using namespace std;
int main() {
//n is the number of elements in the array
int n,largest;
int num[50];
cout<<"Enter number of elements you want to enter: ";
cin>>n;
/* Loop runs from o to n,in such a way that first
* element entered by user is stored in num[0],second
* in num[1] and so on.
*/
for(int i = 0; i < n; i++) {
cout<<"Enter Element "<<(i+1)<< ": ";
cin>>num[i];
}
// Storing first array element in "largest" variable
largest = num[0];
for(int i = 1;i < n; i++) {
/* We are comparing largest variable with every element
* of array. If there is an element which is greater than
* largest variable value then we are copying that variable
* to largest,this way we have the largest element copied
* to the variable named "largest" at the end of the loop
*/
if(largest < num[i])
largest = num[i];
}
cout<<"Largest element in array is: "<<largest;
return 0;
}
输出:
Enter number of elements you want to enter: 5
Enter Element 1: 19
Enter Element 2: 21
Enter Element 3: 3
Enter Element 4: 89
Enter Element 5: 13
Largest element in array is: 89
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。