在 c++ 中查找中间值
Finding middle value in c++
我的代码中有一部分让我感到困惑。首先,我尝试找到 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 算法将使你的代码更具表现力和更易于理解。我建议您从头开始学习它们
先对您的数字进行某种排序,然后您将轻松获得最小值和最大值。之后,只需添加中间数字并用中间数字的总数减去它。
由于您只有四个数字,因此您可以执行以下操作:
float median = (sum(...) - min(...) - max(...)) / 2.0;
您可以累加最小和最大函数值:
int max(int a, int b, int c, int d) { return std::max(std::max(a,b),
std::max(c, d));
}
int min(int a, int b, int c, int d) { return std::min(std::min(a,b),
std::min(c, d));
}
int mid = ((a+b+c+d) - max(a,b,c,d) - min(a,b,c,d))/2;
或者,如果您使用的是 c++11,则可以执行以下操作:
auto values = {a,b,c,d};
decltype(values.begin()) mn, mx;
std::tie(mn, mx) = std::minmax_element(values.begin(), values.end());
auto median = (std::accumulate(values.begin(), values.end(), 0) - *mn - *mx) / 2;
在这里行动:https://ideone.com/69nRvo
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 2D数组来自文本输入,中间有空格
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 在C++中查找范围的长度
- 算法问题:查找从堆栈中弹出的所有序列
- 在Windows中查找扬声器输出的当前音量级别
- 查找中间两个数字的正则表达式的匹配项
- 在 c++ 中查找中间值
- 写入二进制文件的中间;使用tellg()查找长度
- std::multiset并查找中间元素
- C++ 使用函数模板查找任何输入数据类型的中间值
- 查找链表的中间节点
- 在动态数组C++中查找中间数