簡體   English   中英

我怎樣才能在循環中找到最大值?

[英]How would i be able to find the max value in a loop?

我試圖為公寓大樓找到最大的利潤。 我使用循環來查找所有不同的利潤,但我需要找到利潤的最大值。 我怎樣才能找到最大利潤? 我應該使用循環還是其他方式來做到這一點? 我還是編碼新手,非常感謝幫助。

#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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM