gpt4 book ai didi

c++ - 在 C++ 中寻找中间值

转载 作者:行者123 更新时间:2023-11-27 23:48:31 28 4
gpt4 key购买 nike

我对代码的一部分感到困惑。首先,我试图找到 4 个给定数字(随机)的最小值和最大值。然后我需要找到中间数的平均值,这是我的代码,任何帮助将不胜感激,谢谢!

我想我应该使用我在第一部分中使用的最小和最大函数吗?但我不知道该怎么做

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int result;

int min(int a, int b, int c, int d)
{
result = a;
if (b < result) result = b;
if (c < result) result = c;
if (d < result) result = d;
return result;
}

int max(int a, int b, int c, int d)
{
int result = a;
if (b > result) result = b;
if (c > result) result = c;
if (d > result) result = d;
return result;
}

int main()
{
int Min,Max;
Min = min(2,6,3,4);
cout << " The result for minimum is " << Min <<endl;
Max = max(2,6,3,4);
cout << " The result for maximum is " << Max;
}

/**
Computes the average of the middle values of four given values
(that is, without the largest and smallest value).
Hint: Use the given min function. You may also want to define a
max helper function or take advantage of the fact that max can be
computed from the min of the negative values.
**/

/** things got confused after this...the first part is actually finished with the help from my other question **/

int mv1;

double middle(int a, int b, int c, int d)
{
int mv1=a;
if(a<=b)
return a;
}

int main1()
{

int x;
int y;
int z;
int n;
int md;

cout << "Please enter a number: ";
cin>>x;
cout << "Enter another number: ";
cin>>y;
cout << "Enter the third number: ";
cin>>z;
cout << "Enter the fourth number: ";
cin>>n;

md=middle(x,y,z,n);
cout << endl<<"middle is "<<md <<endl;
return 0;


}

最佳答案

你应该开始学习标准模板库,你可以这样做:

#include <vector>
#include <algorithm>
#include <iostream>

double median(int a, int b, int c, int d)
{
std::vector<int> v{a,b,c,d};
std::sort(v.begin(),v.end());
return static_cast<double>(v[1]+v[2])/2;
}

int main() {
std::cout << "median of 1,2,3,4: " << median(1,2,3,4) << "\n";
}

哪些输出:

middle of 1,2,3,4: 2.5

使用 STL 算法将使您的代码更具表现力且更易于理解。我建议你从头开始学习它们

关于c++ - 在 C++ 中寻找中间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48617739/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com