从数组中每 3 个连续选择元素并使用函数进行比较

Select every 3 consecutive elements from an array and comparing them using a function

本文关键字:函数 比较 元素 选择 数组 连续      更新时间:2023-10-16
#include <iostream>
using namespace std;
// function to compare the three values
int maximum(int x, int y, int z) 
{
    int max;
    if (x > y) {
        max = x;
        if (z > max)
            max = z;
    } else {
        max = y;
        if (z > max)
            max = z;
    }
    return max;
}  
// main code
int main() {
    int i, a, b;
    cout << "La dimension de la table?" << endl; 
    // Ask user to select the size of the array, maximum 20. "a" is the size 
    cin >> a;
    while (a > 20) {
        cout << "La dimension maximum est 20! Reessayez!" << endl;
        cin >> a;
    }
    int v1[a];
    // ask user to fill the array
    cout << "Remplisez la table" << endl;
    for (i = 0; i < a; i = i + 1) {
        cin >> v1[i];
    }
    // using this variable to know when the loop should stop
    b = 0; 
    // selecting the 3 consecutive elements to compare
    while (b <= a) {
        for (i = b; i < 4; i = i + 1) { 
         // this is were it should compare the 3 selected values and print them
            cout << "Le maximum est " << maximum(v1[i], v1[i], v1[i]) << endl; 
        }
        // passing to the next 3 values
        b = b + 3; 
    }
}

这是我的完整代码。一切都很好,除了最后一部分,我必须以某种方式选择值并将它们发送到要比较的函数。有什么建议吗?

多谢!

Alex,

你的逻辑在大多数情况下是正确的。话虽如此,我有以下几点意见:

您正在创建一个动态数组,就好像它是一个固定大小的数组一样:

int v1[a];

此数组应按如下方式定义:

int* v1 = int[a];

因为在编译时不知道大小。因此,您需要在运行时在堆中分配内存。另一种选择是按照Chris的建议使用std::vector。

在函数调用的所有三个参数中,您向函数发送相同的值:

maximum(v1[i], v1[i], v1[i]);

这是一个小错字,但会给出错误的结果。

您不需要嵌套循环来选取每三个元素并将它们发送到函数。

尝试:

b=0;
while(b <= (a-3))
{
    maximum(v1[b], v1[b+1], v1[b+2]);
    b+=3;
}

这里 b 需要迭代到 a-3,因为最后三个元素将从该点开始。

最后,您可以按如下方式缩短函数:

int maximum(int x, int y, int z) {
    int max=x;
    if(y>max) max=y;
    if(z>max) max=z;
    return max;
    }

希望对您有所帮助!

我了解,您正在尝试以 3 为一组比较数组中的每个元素。 要完成该用途

for (int i=0; i+2<a; i+=3)
   cout << "Le maximum est " << maximum(v1[i], v1[i+1], v1[i+2]) << endl;