首页 > 解决方案 > 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?

问题描述

我被困在以下部分:

  1. 显示数组的第一个和最后一个元素之间的差异

  2. 如何在此程序中显示指定索引之前的数组元素?

问题描述:

编写一个程序,生成一个由 25 个随机整数组成的数组,每个整数从 3 到 7(使用您的函数 randint() 生成这些数字),并包括以下所有方面。

你的程序

  1. 在 main 中声明数组(不允许使用全局变量!),

  2. 使用您的 randint() 函数将上述数组初始化为随机值 3 到 7

  3. 然后使用下面提供的原型调用函数!

为此,您必须为下面提供的原型编写函数定义:

void showArray ( int a[ ], int size );      // shows the array in the format "int a [ ] = { 3, 7, 4, ... ,5, 6, 3, 4, 7 } "
void showReverse ( int a[ ], int size );    // shows the array in reverse using the format "int a [ ] = { 7, 4, 3, 6, 5, ... , 4, 7, 3 } "
int  lowest ( int a[ ], int size );         // finds and returns the lowest value in the array (should be 7)
int  highest ( int a[ ], int size );        // finds and returns the highest value in the array (should be 3)
int  sumArray ( int a[ ], int size );       // calculates and returns the sum of all values in the array
float averageVal ( int a[ ], int size );    // calculates and returns the average of all values in the array

int count5 ( int a[ ], int size );           // returns how many times the number 5 appears in the array
int firstMinusLast ( int a[ ], int size );   // returns the difference between the First Array Element - Last Array Element
void showBeforeIndex( int a [ ], int size, int index);  // shows all array values before a specified index
void done ( );                   // a function that shows the message "I am now done with CSS1! :) 
int randint(int min, int max);   // a function that returns a random integer between min and max


这是我到目前为止的代码——如何创建数组以显示第一个和最后一个数组元素之间的差异以及确定在指定索引(例如索引 3)之前显示数组元素的方法?


#include <time.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

void showArray ( int a[ ], int size ); // shows the array in the format "int a [ ] = { 3, 7, 4, ... ,5, 6, 3, 4, 7 } "

void showReverse ( int a[ ], int size );
int  lowest ( int a[ ], int size );
int highest ( int a[ ], int size );
int  sumArray ( int a[ ], int size );
float averageVal ( int a[ ], int size );
int count5 ( int a[ ], int size );                              // returns how many times the number 5 appears in the array
int firstMinusLast ( int a[ ], int size );                      // returns the difference between the First Array Element - Last Array Element
void showBeforeIndex( int a [ ], int size, int index);          // shows all array values before a specified index
void done ();      
int randint(int min, int max);                                  // a function that returns a random integer between min and max

int main ()
{
    srand((int)time(NULL));
    int i = 0;
    const int size = 25; // size variable for arrays
    int randint[size], lowest, highest;


    cout << "Making an array of 25 random integers from 3 to 7!\n";
    cout << "\n";
    cout << "Original array a [ ] = {";

    for(i; i < size; i++)
    {
        randint[i] = 3 + rand () % 5; // random number between 3 to 7
    }

     showArray(randint, size); // pass the array and its SIZE to function
     cout << "}\n";

    // Reversed array
     // One way to reverse an array is to swap the first and last value,
    // then swap the second and second-to-last value,
    // then swap the third and third-to-last value, and so on...
    cout << "\n" << "Reversed array a [ ] = { ";

    int j = size-1; // initialize j to the last index
    i = 0;  // set i to the beginning index (i.e. index 0)

    while( i <= j)  // keep loop until i and j cross over
    {
        std::swap(randint[i], randint[j]); // swap the values at i-th and j-th index
        i++; // move i forwards
        j--; // move j backwards
    }

    showReverse(randint, size);
    cout << "}\n";

    lowest=randint[0];
    highest=randint[0];

    for (i = 0; i < size; i++)
    {
        if(randint[i]<lowest)
            lowest=randint[i];
        if(randint[i]>highest)
            highest=randint[i];
    }

    cout<<"\nLowest value is : "<<lowest <<"\n";
    cout<<"\nHighest value is : "<<highest <<"\n";


    int sum=0;


    for (int a=0; a<size; a++)
    {
        sum+=randint[a];
    }

    cout << "\nThe sum of all array elements is " << sum << endl;

    float average=sum/size;

    cout << "\nThe average of all array values is " << average << endl;


    int numsearch = 5;

    int counter = 0;
    for(int i = 0; i < size; i++)
        if(randint[i] == numsearch)
            counter++;
    std::cout << "\nThe number 5 appears " << counter <<" times.\n";

    std::cout << firstMinusLast;

    return 0;
}

// Function definitions
void showArray ( int a[ ], int size )
{
     for(int i = 0; i < size; i++) std::cout << a[i] << " ";
}

void showReverse ( int a[ ], int size )
{
     for(int i = 0; i < size; i++) std::cout << a[i] << " ";

}

int count5(int numsearch, int randint[], int size)
{
    int counter = 0;
    for(int a = 0; a < size; a++)
        if(randint[a] == numsearch)
            counter++;
    return counter;
}

int first (int size)  /// find the first digit
    {
        while (size >=25)
            size /= 25;

        return size;
    }

int last (int size)  /// find the first digit
    {
        return (size%25);
    }

int firstMinusLast ( int a[ ], int size )
{
    int first = -1, last = -1;
    for (int i=0; i<size; i++)
{
    if (a != rand[i])
        continue;
    if (first == -1)
        first = i;
    last = i;
}
if (first != -1)
    cout << "First minus last = " << first-last;

}

/* SAMPLE RUN:
ERRORS – will not compile; errors say: 
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
|In function 'int firstMinusLast(int*, int)'|
|214|warning: pointer to a function used in arithmetic [-Wpointer-arith]|
|214|error: comparison between distinct pointer types 'int*' and 'int   (__attribute__((__cdecl__)) *)()' lacks a cast [-fpermissive]|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s))     
*/

标签: c++arrays

解决方案


您的问题非常混乱,并且包含不需要的代码。但是,我可以指出的一件事是,您用于汇总和平均数组元素的函数似乎已经以某种方式与main().

请将它们分开并仅在main(). (请注意,您可以使用求和函数来计算平均值)。

关于您的第一个问题,您可以计算数组的第一个和最后一个元素之间的差异,如下所示:

int firstMinusLast(int a[], int size)
{
    return(a[0] - a[size-1]);
}

因为第一个元素的索引始终为零,并且无论如何都必须提供最后一个元素的索引。

要在指定索引之前显示数组的元素,您需要遍历它们直到索引达到指定值:

void ShowBeforeIndex(int a[], int size, int index)
{
    for(int Ix = 0; Ix < index; Ix++)
        cout << a[Ix] << " ";
}

请注意,只要您相信用户使用正确的索引调用函数,就不需要指定大小。


推荐阅读