gpt4 book ai didi

c++ - 编写重新排序函数

转载 作者:行者123 更新时间:2023-11-30 05:37:33 24 4
gpt4 key购买 nike

我必须编写一个函数,将三个变量从低到高重新排序。函数名称是 void reorder,我很好奇我是否可以在此函数内部调用我的 max 和 min 函数以压缩我的代码,或者是否有一种方法可以不使用 IF 语句来编写它。我已经开始了,我想知道在继续之前该怎么做。谢谢

#include <cstdlib>
#include <cmath>
#include <iostream>
#include <iomanip>

using namespace std;

/*
*
*/

int min3int(int a, int b, int c)
// function returns the minimum of 3 integer inputs
//@
//@
{
if(a<b)
{
if(a<c)
{
return a;
}
}
else if(b<a)
{
if(b<c)
{
return b;
}
}
else if (c<a)
{
if(c<b)
{
return c;
}
}
}
int max3int(int a, int b, int c)
// function returns the maximum of 3 integer inputs
//@
//@
{
if(a>b)
{
if(a>c)
{
return a;
}
}
else if(b>a)
{
if(b>c)
{
return b;
}
}
else if (c>a)
{
if(c>b)
{
return c;
}
}
}
void reorder(int min,int med,int max);
// function reorders the 3 reference parameters so that they are in ascending order
//@
//@
int temp;

if(min<med)
{
if(med<max)
{
if(min<max)
{
min=min;
med=med;
max=max;
}
else if(med<min)
{
if (med<max)
{
if (max<)
}
}

}
}

bool isFactor(int num1,int num2);
// function checks if the first int is a factor of the second int.

int main(int argc, char** argv) {

int dividend;
int factor1, factor2, factor3;

cout << "Enter the number to be divided: ";
cin >> dividend;

cout << endl << "Enter the first possible factor: ";
cin >> factor1;

cout << endl << "Enter the second possible factor: ";
cin >> factor2;

cout << endl << "Enter the third possible factor: ";
cin >> factor3;

cout << endl << "Possibilites entered are in the range of " << min3int(factor1,factor2,factor3)
<< " to " << max3int(factor1,factor2,factor3) << "." << endl;

reorder(factor1,factor2,factor3);

cout << endl << "The following numbers were determined to be factors of " << dividend << ": ";
if(isFactor(factor1,dividend))
cout << factor1 << " ";
if(isFactor(factor2, dividend))
cout << factor2 << " ";
if(isFactor(factor3, dividend))
cout << factor3;

cout << endl << endl;


return 0;
}

最佳答案

我将这三个值放在一个 vector 中并调用排序算法。这提供了一个没有 if 语句的整洁干净的函数

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

using namespace std;

void reorder(int &min, int &med, int &max)
{
vector<int> vec;
vec.push_back(min);
vec.push_back(med);
vec.push_back(max);

sort(vec.begin(), vec.end());

min = vec[0];
med = vec[1];
max = vec[2];
}

int main()
{
int min = 1, med = 1, max = 3;
cout << min << " " << med << " " << max << endl;
reorder(min, med, max);
cout << min << " " << med << " " << max << endl;
system("pause");
return 0;
}

关于c++ - 编写重新排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33176177/

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