如何求最小最大总和 c++
我用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有2个问题。
我将向您展示错误所在以及如何重构它。
但首先也是最重要的是:在开始编码之前,您需要思考。至少1天。之后,拿一张纸画出你的解决方案的想法。多次重构这个想法,这将花费整整一天的时间。
然后,开始编写代码。这将需要 3 分钟,如果你做得高质量,则需要 10 分钟。
让我们首先看看您的代码。我会在源码中添加注释来指出一些问题。请参阅:
基本上,您从总和中仅减去一个值的想法是正确的。但并不需要一直计算总和。
将代码重构为可行但仍不是最佳的 C++ 解决方案可能如下所示:
There are 2 problems.
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:
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: