我很难创建一个void / reference函数来确定最高和最低的数字。这些数字先前输入并分配给四个单独的变量。数字的范围只有0到100.我不能使用数组,它必须是一个函数。我的老师说他能够完成6个条件,我接近12个。
void GetGradesFromUser(double& grade1, double& grade2, double& grade3, double& grade4)
{
cout << "Enter four test grades: ";
cin >> grade1 >> grade2 >> grade3 >> grade4;
}
double DetermineMaxAndMin(double& grade1, double& grade2, double& grade3, double& grade4)
{
double max;
double min;
if (grade1 >= grade2 && grade1 >= grade3 && grade1 >= grade4)
{
max = grade1;
}
else if (grade2 >= grade1 && grade2 >= grade3 && grade2 >= grade4)
{
max = grade2;
}
else if (grade3 >= grade1 && grade3 >= grade2 && grade3 >= grade4)
{
max = grade3;
}
else max = grade4;
if (grade1 <= grade2 && grade1 <= grade3 && grade1 <= grade4)
{
min = grade1;
}
else if (grade2 <= grade1 && grade2 <= grade3 && grade2 <= grade4)
{
min = grade2;
}
else if (grade3 <= grade1 && grade3 <= grade2 && grade3 <= grade4)
{
min = grade3;
}
else min = grade4;
}
答案 0 :(得分:-1)
如果您不能使用数组和循环,并希望在不超过6个条件的情况下获得结果,请考虑以下事项:
double DetermineMaxAndMin(double& grade1, double& grade2, double& grade3, double& grade4)
{
double max = grade1;
double min = grade1;
//find max
if (max < grade2) max = grade2;
if (max < grade3) max = grade3;
if (max < grade4) max = grade4;
//find min
if (min > grade2) min = grade2;
if (min > grade3) min = grade3;
if (min > grade4) min = grade4;
}
诀窍是假设你已经找到了最大/最小值,并在与新值进行比较时替换它的值。
答案 1 :(得分:-2)
int a [101]; int min = 0; int max = 0;
min = a [0]; MAX = A [0];
for(int i = 0; i&lt; 101; i ++){if(min&gt; a [i]){min = a [i];}; if(max&lt; a [i]){max = a [i];}; };
所以如果你的号码是1 2 3 4;
min = 1; max = 1;最小值为1 1 1 1;每次迭代; 最大值为1 2 3 4;每次迭代;
这是数组daaa的示例。但如果你足够聪明,你可以运用我的方法。你只需要调整我的代码并删除数组部分。
P.S。该代码包含2个条件并对任意数量的数字进行排序。它非常基本,你可以肯定地做到这一点。