【问题标题】:Finding minimum/maximum/average values of a sequence in C++在 C++ 中查找序列的最小/最大值/平均值
【发布时间】:2012-09-27 05:36:55
【问题描述】:

我正在创建一个模拟蓄水池注水的程序。到目前为止,该过程一切顺利,除了我想做的最后一件事是获取填充水库所需的最大、最小和平均年数。我想在不使用数组的情况下这样做。我想我已经很接近了,但我一定错过了一些简单的东西。原谅我,我只是在学习 C++。

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>
#include <ctime>

using namespace std;




int main ()
{

    string operation;
    do{
    cout << "Using the letters 's', or 'q', please indicate if you would like to run a simulation, or quit the program: " << endl;
    cin >> operation;
    } while (operation != "s" && operation != "q");
    string reservoir_name; // Creating variables for reservoir
    double reservoir_capacity;
    double outflow;
    double inflow_min;
    double inflow_max;

    if (operation == "q")
    {
        cout << endl;
        cout << "This was a triumph . . ." << endl;
        cout << "I'm making a note here: huge success!" << endl;
        system ("pause");
        return 0;
    }

    while (operation == "s") 
        {

                string reservoir_name; // Creating variables
                double reservoir_capacity;

                double inflow_min = 0;
                double inflow_max = 0;
                double inflow_average = inflow_min + inflow_max;
                double inflow_difference = inflow_max - inflow_min;
                double inflow_threshold = .9 * inflow_average/2; // Math for acceptable flow threshold.



                cout << "What is the name of the reservoir?" << endl;
                cin.ignore ();
                getline (cin,reservoir_name); // Grab whole string for reservoir name.
                cout << "What is the capacity of the reservoir in MAF (Millions of Acre Feet)?" << endl;
                cin >> reservoir_capacity;
                cout << "What is the minimum inflow?" << endl;
                cin >> inflow_min;
                cout << "What is the maximum inflow?" << endl;
                cin >> inflow_max;
                cout << "What is the required outflow?" << endl;
                cin >> outflow;
                cout << endl;
                inflow_average = inflow_min + inflow_max;
                inflow_threshold = .9 * inflow_average/2; // Calculate threshold for too much outflow.
                cin.ignore ();

                if (outflow > inflow_threshold) // Check for unacceptable outflow levels.
                {
                    cout << "Warning! The outflow is over 90% of the average inflow. Simulation aborted. Returning to main menu." << endl << endl;
                }
                else
                {
                    const int number_simulations = 10;
                    cout << endl;
                    cout << "Reservoir name: " << reservoir_name << endl;
                    cout << "Capacity of reservoir in MAF: " << reservoir_capacity << endl;
                    cout << "Maximum inflow in MAF: " << inflow_max << endl;
                    cout << "Minimum inflow in MAF: " << inflow_min << endl;
                    cout << "Required outflow in MAF: " << outflow << endl << endl;

                    cout << "Running simulation . . ." << endl << endl;
                    srand (time(0));
                    const int sentinel = -1;
                    int minimum = sentinel;
                    int maximum = sentinel;
                    int years_total;
                    for (int i = 1; i <= number_simulations; i++) // Loop should run the filling simulation 10 times.
                    {

                        int years = 0;
                        double fill_level = 0;
                        for (years; fill_level < reservoir_capacity; years++ ) // Loop should simulate filling reservoir using random inflow values between inflow_min and inflow_max.
                        {

                            double r = rand() * 1.0 / RAND_MAX;
                            double x = inflow_min + (inflow_max - inflow_min) * r;// SHOULD be between minimum inflow and maximum inflow.
                            // cout << "Random Number x :" << x << endl; WAS USED TO CHECK IF RANDOM NUMBER WAS CHANGING
                            fill_level = fill_level + x - outflow;
                            if (fill_level < 0)
                            {
                            fill_level = 0; // Prevent fill level from going negative.
                            }
                            //cout << "Fill level is " << fill_level << endl; TO CHECK THE CHANGE IN FILL LEVEL PER ITERATION
                            if (minimum == sentinel || years < minimum) // Trying to set up the method for retrieving minimum value here. Currently returning as 0.
                            {
                                minimum = years;
                            }
                            if (maximum == sentinel || years > maximum) // Trying to set up the method for retrieving maximum value here. Currently returning as 1 less than the actual maximum.
                            {
                                maximum = years;
                            }
                        }   // Simulate the change of water level.

                        cout << "Simulation " << i << ": The reservoir took " << years << " years to fill." << endl;

                    }

                        cout << "The minimum number of years needed to fill: " << minimum << endl;
                        cout << "The maximum number of years needed to fill: " << maximum << endl;
                        cout << "The average number of years needed to fill: " << years_total / 10 << endl; // Take the running total of years over 10 simulations and divide by 10. Currently returning as 0.
                }
                    cout << endl;
                    cout << "What would you like to do now?" << endl << endl; // Saving for later. The menu re-prompt message and code.
                    cout << "Using the letters 's', or 'q', please indicate if you would like to run a simulation or quit the program: " << endl;
                    cin >> operation;
                    if (operation == "q")
                    {
                        cout << endl;
                        cout << "This was a triumph . . ." << endl;
                        cout << "I'm making a note here: huge success!" << endl;
                        system ("pause");
                        return 0;
                    }
    }


    system ("pause");
    return 0;
}

【问题讨论】:

  • 你目前的结果是什么?你在期待什么?要进行测试,您应该使用知道结果的静态值而不是随机值。
  • 您的问题是什么?您需要帮助设计算法吗?您需要调试方面的帮助吗?什么是错误?如果您逐行浏览代码会发生什么?您是否尝试过将程序缩减为仍然存在问题的最小程序?

标签: c++ average max minimum


【解决方案1】:

既然我们在谈论 C++,我觉得有必要提及可以(极大地)提供帮助的标准 C++ 库操作:

  • std::minmax_element 返回包含集合的最小值和最大值的对(还有 std::min_elementstd::max_element 可用)。
  • std::accumulate,初始化为0时,返回一个集合的元素之和;平均距离不远。

当然,如果您希望同时拥有 3 个,这有点不太理想,因为这意味着两次遍历集合而不是一次。然而,它仍然是 O(N) 时间和 O(1) 空间,并且减少了必须编写的代码。

【讨论】:

    【解决方案2】:

    您需要添加到years_total:

    years_total += years;
    

    您需要将minimummaximum 的设置移动到外部 for 循环。您可以使用不同的最小值和最大值设置来取消 sentinel。见下文:

    #include <iostream>
    #include <cstdlib>
    #include <cmath>
    #include <string>
    #include <ctime>
    
    using namespace std;
    
    int main ()
    {
    
        string operation;
        do{
        cout << "Using the letters 's', or 'q', please indicate if you would like to run a simulation, or quit the program: " << endl;
        cin >> operation;
        } while (operation != "s" && operation != "q");
        string reservoir_name; // Creating variables for reservoir
        double reservoir_capacity;
        double outflow;
        double inflow_min;
        double inflow_max;
    
        if (operation == "q")
        {
            cout << endl;
            cout << "This was a triumph . . ." << endl;
            cout << "I'm making a note here: huge success!" << endl;
            system ("pause");
            return 0;
        }
    
        while (operation == "s") 
            {
    
                    string reservoir_name; // Creating variables
                    double reservoir_capacity;
    
                    double inflow_min = 0;
                    double inflow_max = 0;
                    double inflow_average = inflow_min + inflow_max;
                    double inflow_difference = inflow_max - inflow_min;
                    double inflow_threshold = .9 * inflow_average/2; // Math for acceptable flow threshold.
    
    
    
                    cout << "What is the name of the reservoir?" << endl;
                    cin.ignore ();
                    getline (cin,reservoir_name); // Grab whole string for reservoir name.
                    cout << "What is the capacity of the reservoir in MAF (Millions of Acre Feet)?" << endl;
                    cin >> reservoir_capacity;
                    cout << "What is the minimum inflow?" << endl;
                    cin >> inflow_min;
                    cout << "What is the maximum inflow?" << endl;
                    cin >> inflow_max;
                    cout << "What is the required outflow?" << endl;
                    cin >> outflow;
                    cout << endl;
                    inflow_average = inflow_min + inflow_max;
                    inflow_threshold = .9 * inflow_average/2; // Calculate threshold for too much outflow.
                    cin.ignore ();
    
                    if (outflow > inflow_threshold) // Check for unacceptable outflow levels.
                    {
                        cout << "Warning! The outflow is over 90% of the average inflow. Simulation aborted. Returning to main menu." << endl << endl;
                    }
                    else
                    {
                        const int number_simulations = 10;
                        cout << endl;
                        cout << "Reservoir name: " << reservoir_name << endl;
                        cout << "Capacity of reservoir in MAF: " << reservoir_capacity << endl;
                        cout << "Maximum inflow in MAF: " << inflow_max << endl;
                        cout << "Minimum inflow in MAF: " << inflow_min << endl;
                        cout << "Required outflow in MAF: " << outflow << endl << endl;
    
                        cout << "Running simulation . . ." << endl << endl;
                        srand (time(0));
                        int minimum = reservoir_capacity + 10;
                        int maximum = -1;
                        int years_total;
                        for (int i = 1; i <= number_simulations; i++) // Loop should run the filling simulation 10 times.
                        {
    
                            int years = 0;
                            double fill_level = 0;
                            for (years; fill_level < reservoir_capacity; years++ ) // Loop should simulate filling reservoir using random inflow values between inflow_min and inflow_max.
                            {
    
                                double r = rand() * 1.0 / RAND_MAX;
                                double x = inflow_min + (inflow_max - inflow_min) * r;// SHOULD be between minimum inflow and maximum inflow.
                                // cout << "Random Number x :" << x << endl; WAS USED TO CHECK IF RANDOM NUMBER WAS CHANGING
                                fill_level = fill_level + x - outflow;
                                if (fill_level < 0)
                                {
                                    fill_level = 0; // Prevent fill level from going negative.
                                }
                                //cout << "Fill level is " << fill_level << endl; TO CHECK THE CHANGE IN FILL LEVEL PER ITERATION
                            }   // Simulate the change of water level.
    
                            if (years < minimum) // Trying to set up the method for retrieving minimum value here. Currently returning as 0.
                            {
                                minimum = years;
                            }
                            if (years > maximum) // Trying to set up the method for retrieving maximum value here. Currently returning as 1 less than the actual maximum.
                            {
                                maximum = years;
                            }
                            years_total += years;
                            cout << "Simulation " << i << ": The reservoir took " << years << " years to fill." << endl;
    
                        }
    
                            cout << "The minimum number of years needed to fill: " << minimum << endl;
                            cout << "The maximum number of years needed to fill: " << maximum << endl;
                            cout << "The average number of years needed to fill: " << years_total / 10 << endl; // Take the running total of years over 10 simulations and divide by 10. Currently returning as 0.
                    }
                        cout << endl;
                        cout << "What would you like to do now?" << endl << endl; // Saving for later. The menu re-prompt message and code.
                        cout << "Using the letters 's', or 'q', please indicate if you would like to run a simulation or quit the program: " << endl;
                        cin >> operation;
                        if (operation == "q")
                        {
                            cout << endl;
                            cout << "This was a triumph . . ." << endl;
                            cout << "I'm making a note here: huge success!" << endl;
                            system ("pause");
                            return 0;
                        }
        }
    
    
        system ("pause");
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 2015-01-16
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 2014-01-13
      相关资源
      最近更新 更多