数组中的第一个元素减去最后一个元素
First minus last element in an array
我写了一些代码,可以打印3到7之间的25个随机数,并将它们放入一个数组,然后放入其反向数组。现在如何减去数组中的第一个数字减去数组中最后一个数字?这是我迄今为止的代码。我已经完成了函数调用和原型;只是不确定在定义中到底应该放什么:
#include <time.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
// Function prototypes
void showArray ( int a[ ], int size ); // shows the array in the format "int a [ ] = { 3, 7, 4, ... ,5, 6, 3, 4, 7 } "
void showBeforeIndex( int a [ ], int size, int index); // shows all array values before a specified index
int firstMinusLast ( int a[ ], int size );
// **************************************************************************************************************************************
int main ()
{
// Array and reverse array
srand((int)time(NULL));
int i=0;
const int SIZE = 25;
int randvalue[SIZE];
cout << "Making an array of 25 random integers from 3 to 7!" << endl;
for(; i < SIZE; i++)
{
randvalue[i] = rand () % 5 + 3; // random number between 3 to 7
}
cout << "Original array a [ ] = {";
showArray(randvalue, SIZE);
cout << "}" << endl;
int j = SIZE-1;
i = 0;
while( i <= j)
{
swap(randvalue[i], randvalue[j]);
i++;
j--;
}
cout << "Reversed array a [ ] = {";
showArray(randvalue, SIZE);
cout << "}" << endl;
// *******************************************************************************************************
// Function call for FIRST - LAST
int returnFirstLast = firstMinusLast (randvalue, 25);
cout << "The difference between the first and and last array elements is " << returnFirstLast << endl;
//********************************************************************************************************
return 0;
}
// Function definition for ARRAY
void showArray ( int a[ ], int size )
{
int sum = 0;
for(int i = 0; i < size; i++)
cout << a[i];
}
// Function definition for FIRST - LAST
int firstMinusLast ( int a[ ], int size )
{
int fml;
return fml;
}
在C/C++中,数组以0开头进行索引。所以第一个元素在索引0处。假定数组的第一个元素位于索引0处,则数组的最后一个元素位于等于数组大小减1的索引处。因此代码:
第一个元素是a[0]
最后一个元素是a[SIZE - 1]
所以为了得到它们的区别:fml
你只需写:fml = a[0] - a[SIZE - 1]
对于一个函数来说,这似乎很简单,所以也许你期待的是更大或不同的东西。
你需要差值的绝对值吗?没有符号的变化幅度?如果是,只需使用绝对值函数。
fml = abs(a[0] - a[SIZE-1]);
如果你想说你想在反转之前先减去最后一个,那么简单地做一下:
fml = a[SIZE-1] - a[0];
如果它需要abs
,那么用哪种方式做减法都无关紧要。
如果您已经有了数组的大小,并且您知道数组已完全填充:
int firstMinusLast ( int a[ ], int size ){
return a[0] - a[size - 1];
}
相关文章:
- lower_bound()返回最后一个元素
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 仅显示链表的最后一个元素
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- std::矢量保存 只推送最后一个元素
- 反转后不返回最后一个元素
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 在 QListView 中显示最后一个元素
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 遍历列表包含排除最后一个元素的内容
- 如何打印第一个和最后一个元素的和,然后打印第二个和倒数第二个元素的总和,依此类推
- C++链表最后一个元素的迭代器?
- 这种获取模板参数包中最后一个元素的方法是否有隐藏的开销?
- 使用 STL 交换堆栈 C++ 中的第一个和最后一个元素
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?