如何求最小最大总和 c++

发布于 2025-01-13 16:20:59 字数 917 浏览 0 评论 0原文

我用 C++ 编写了一些代码,旨在找到可以通过对数组中呈现的 5 个整数中的 4 个求和来计算的最小值和最大值。我的想法是,我可以将数组的所有元素相加,然后循环减去每个元素,以找出哪个减法会导致最小和最大的总数。我知道这不是最聪明的方法,但我只是好奇为什么这种强力方法在我编码时不起作用。任何反馈将不胜感激。

#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;

void minimaxsum(vector<int> arr){
    int i,j,temp;
    int n=sizeof(arr);
    int sum=0;
    int low=INT_MAX;
    int high=0;

    for (j=0;j<n;j++){
        for (i=0;i<n;i++){
            sum+=arr[i];
        }
        temp=sum-arr[j];
        if(temp<low){
            low=temp;
        }
        else if(temp>high){
            high=temp;
        }
    }
    cout<<low;
    cout<<high<<endl;
}

int main (){
    vector<int> arr;
    arr.push_back(1.0);
    arr.push_back(2.0);
    arr.push_back(3.0);
    arr.push_back(1.0);
    arr.push_back(2.0);
    minimaxsum(arr);
    return 0;
}

I've written some code in c++ that is meant to find the minimum and maximum values that can be calculated by summing 4 of the 5 integers presented in an array. My thinking was that I could add up all elements of the array and loop through subtracting each of the elements to figure out which subtraction would lead to the smallest and largest totals. I know this isn't the smartest way to do it, but I'm just curious why this brute force method isn't working when I code it. Any feedback would be very much appreciated.

#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;

void minimaxsum(vector<int> arr){
    int i,j,temp;
    int n=sizeof(arr);
    int sum=0;
    int low=INT_MAX;
    int high=0;

    for (j=0;j<n;j++){
        for (i=0;i<n;i++){
            sum+=arr[i];
        }
        temp=sum-arr[j];
        if(temp<low){
            low=temp;
        }
        else if(temp>high){
            high=temp;
        }
    }
    cout<<low;
    cout<<high<<endl;
}

int main (){
    vector<int> arr;
    arr.push_back(1.0);
    arr.push_back(2.0);
    arr.push_back(3.0);
    arr.push_back(1.0);
    arr.push_back(2.0);
    minimaxsum(arr);
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

末骤雨初歇 2025-01-20 16:20:59

有2个问题。

  1. 不幸的是,您的代码有错误,无法提供正确的结果。
  2. 解决方案方法,设计是错误的,

我将向您展示错误所在以及如何重构它。

但首先也是最重要的是:在开始编码之前,您需要思考。至少1天。之后,拿一张纸画出你的解决方案的想法。多次重构这个想法,这将花费整整一天的时间。

然后,开始编写代码。这将需要 3 分钟,如果你做得高质量,则需要 10 分钟。

让我们首先看看您的代码。我会在源码中添加注释来指出一些问题。请参阅:

#include <iostream>
#include <vector>
#include <limits.h>   // Do not use .h include files from C-language. Use limits
using namespace std;  // Never open the complete std-namepsace. Use fully qualified names

void minimaxsum(vector<int> arr) {  // Pass per reference and not per value to avoid copies
    int i, j, temp;                 // Always define variables when you need them, not before. Always initialize
    int n = sizeof(arr);            // This will not work. You mean "arr.size();"
    int sum = 0;
    int low = INT_MAX;              // Use numeric_limits from C++
    int high = 0;                   // Initialize with MIN value. Otherwise it will fail for negative integers

    for (j = 0; j < n; j++) {       // It is not understandable, why you use a nested loop, using the same parameters
        for (i = 0; i < n; i++) {   // Outside sum should be calculated only once 
            sum += arr[i];          // You will sum up always. Sum is never reset
        }
        temp = sum - arr[j];
        if (temp < low) {
            low = temp;
        }
        else if (temp > high) {
            high = temp;
        }
    }
    cout << low;                    // You miss a '\n' at the end
    cout << high << endl;           // endl is not necessary for cout. '\n' is sufficent
}

int main() {
    vector<int> arr;               // use an initializer list
    arr.push_back(1.0);            // Do not push back doubles into an integer vector
    arr.push_back(2.0);
    arr.push_back(3.0);
    arr.push_back(1.0);
    arr.push_back(2.0);
    minimaxsum(arr);
    return 0;
}

基本上,您从总和中仅减去一个值的想法是正确的。但并不需要一直计算总和。

将代码重构为可行但仍不是最佳的 C++ 解决方案可能如下所示:

#include <iostream>
#include <vector>
#include <limits>

// Function to show the min and max sum from 4 out of 5 values
void minimaxsum(std::vector<int>& arr) {

    // Initialize the resulting values in a way, the the first comparison will always be true
    int low = std::numeric_limits<int>::max();
    int high = std::numeric_limits<int>::min();;              

    // Calculate the sum of all 5 values
    int sumOf5 = 0;
    for (const int i : arr)
        sumOf5 += i;
    
    // Now subtract one value from the sum of 5
    for (const int i : arr) {
        if (sumOf5 - i < low)       // Check for new min
            low = sumOf5 - i;
        if (sumOf5 - i > high)      // Check for new max
            high = sumOf5 - i;      
    }
    std::cout << "Min: " << low << "\tMax: " << high << '\n';
}

int main() {
    std::vector<int> arr{ 1,2,3,1,2 };   // The test Data
    minimaxsum(arr);                     // Show min and max result
}

There are 2 problems.

  1. Your code is unfortunately buggy and cannot deliver the correct result.
  2. The solution approach, the design is wrong

I will show you what is wrong and how it could be refactored.

But first and most important: Before you start coding, you need to think. At least 1 day. After that, take a piece of paper and sketch your solution idea. Refactor this idea several times, which will take a complete additional day.

Then, start to write your code. This will take 3 minutes and if you do it with high quality, then it takes 10 minutes.

Let us look first at you code. I will add comments in the source code to indicate some of the problems. Please see:

#include <iostream>
#include <vector>
#include <limits.h>   // Do not use .h include files from C-language. Use limits
using namespace std;  // Never open the complete std-namepsace. Use fully qualified names

void minimaxsum(vector<int> arr) {  // Pass per reference and not per value to avoid copies
    int i, j, temp;                 // Always define variables when you need them, not before. Always initialize
    int n = sizeof(arr);            // This will not work. You mean "arr.size();"
    int sum = 0;
    int low = INT_MAX;              // Use numeric_limits from C++
    int high = 0;                   // Initialize with MIN value. Otherwise it will fail for negative integers

    for (j = 0; j < n; j++) {       // It is not understandable, why you use a nested loop, using the same parameters
        for (i = 0; i < n; i++) {   // Outside sum should be calculated only once 
            sum += arr[i];          // You will sum up always. Sum is never reset
        }
        temp = sum - arr[j];
        if (temp < low) {
            low = temp;
        }
        else if (temp > high) {
            high = temp;
        }
    }
    cout << low;                    // You miss a '\n' at the end
    cout << high << endl;           // endl is not necessary for cout. '\n' is sufficent
}

int main() {
    vector<int> arr;               // use an initializer list
    arr.push_back(1.0);            // Do not push back doubles into an integer vector
    arr.push_back(2.0);
    arr.push_back(3.0);
    arr.push_back(1.0);
    arr.push_back(2.0);
    minimaxsum(arr);
    return 0;
}

Basically your idea to subtract only one value from the overall sum is correct. But there is not need to calculate the overall sum all the time.

Refactoring your code to a working, but still not an optimal C++ solution could look like:

#include <iostream>
#include <vector>
#include <limits>

// Function to show the min and max sum from 4 out of 5 values
void minimaxsum(std::vector<int>& arr) {

    // Initialize the resulting values in a way, the the first comparison will always be true
    int low = std::numeric_limits<int>::max();
    int high = std::numeric_limits<int>::min();;              

    // Calculate the sum of all 5 values
    int sumOf5 = 0;
    for (const int i : arr)
        sumOf5 += i;
    
    // Now subtract one value from the sum of 5
    for (const int i : arr) {
        if (sumOf5 - i < low)       // Check for new min
            low = sumOf5 - i;
        if (sumOf5 - i > high)      // Check for new max
            high = sumOf5 - i;      
    }
    std::cout << "Min: " << low << "\tMax: " << high << '\n';
}

int main() {
    std::vector<int> arr{ 1,2,3,1,2 };   // The test Data
    minimaxsum(arr);                     // Show min and max result
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文