从数组中每 3 个连续选择元素并使用函数进行比较
Select every 3 consecutive elements from an array and comparing them using a function
#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;
相关文章:
- C++自定义比较函数
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- C++模板函数,用于比较任何无符号整数和有符号整数
- 函数类作为比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- std::max() 函数与定点实现的比较中的问题
- 如何比较两个函数的速度和性能
- 对没有比较器或λ函数的向量进行排序?
- 使用迭代器的自定义比较器函数
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 比较 n 女王的 next_permutation 函数
- 用于基于成员字段或函数创建比较器的快捷方式
- 为什么 std::stable_sort() 的比较函数的参数必须是设置常量?
- 为什么在类或结构中传递自定义比较器函数?
- 浮点数比较为什么没有相等的函数
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- 为什么函数比较器不像在排序中那样在优先级队列中工作?
- c++ STL集合的比较函数:比较函数可以是类的成员函数吗?
- 联合值的单函数比较