我的功能有问题。当我使用一个函数来操作一个数组,并打印它并移动到下一个操作函数时,它使用之前操作的数组而不是原始数组。例如,当我的函数将每个负数转换为正数时,我调用下一个函数将所有偶数清零,并且我的数组打印出所有零,而不是使用原始数组。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#define NUMS_PER_LINE 10 // maximum numbers to be printed on each line.
int numbers[100]; // array to hold upto 100 integer numbers.
int numcnt; // actual count (<=100) of numbers in above array.
// reads file content into array
void read_array_from_file (const char filename[])
{
ifstream inpfile(filename);
if (!inpfile.is_open())
{
cout << "Can't open file : " << filename << endl;
exit(1);
}
numcnt=0; // Initialise count of read numbers
// Read numbers from the file into array.
inpfile >> numbers[numcnt];
while (!inpfile.eof()) // Read until EOF is reached.
{
numcnt++; // Got one more number from input file.
inpfile >> numbers[numcnt];
}
inpfile.close();
return;
}
// Print out all the values in the array
void print_array_content (int numsinaline)
{
int i;
for (i=0; i<numcnt+1; i++)
{
if ((i % numsinaline) == 0)
cout << endl;
cout << numbers[i] << " ";
}
cout << endl << endl;
return;
}
// calculate average
double calculate_average ()
{
int i;
float sum=0;
for (i=0; i<(numcnt-1); i++)
{
sum += numbers[i];
}
return (sum/(numcnt-1));
}
// Find numbers larger and smaller than the average.
void find_numbers_smaller_and_larger_than_average (int &larger, int &smaller, int average)
{
int i;
for (i=0; i<(numcnt-1); i++)
{
if (numbers[i] < average)
smaller++;
else if (numbers[i] > average)
larger++;
}
return;
}
// Convert negative numbers to positive in the array 'numbers'.
void convert_negative_to_positive ()
{
int i;
for (i=0; i<(numcnt-1); i++)
{
if (numbers[i] < 0)
numbers[i] *= -1;
}
return;
}
// Convert all even numbers into zero.
void zero ()
{
int i;
for (i=0; i<numcnt; i++)
{
if (numbers[i] > 0)
numbers[i] *= 0;
}
return;
}