我无法弄清楚如何将sales[]
数组传递给BubbleSort()
函数。我得到的错误是销售未在此范围内声明,就像它是一个未声明的变量。这是我遇到的唯一问题。如果我不调用该函数,程序运行正常。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void BubbleSort(int arr[], int n)
{
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
int main() {
//Variables
//String to hold user data file
string fileName;
//Double to hold calculated sales average
double averageSales;
// Double to hold total sales
double totalSales;
// Int to read array size
int arraySize;
// Double to hold highest sales value
double highest = 0;
// Double to hold lowest sales value
double lowest;
// Char to hold rerun choice, default value is no
char rerun = 'n';
//Do / While loop for rerun choice
do {
//Get File Name from User
cout << "Input Filename to read:" << endl;
cin >> fileName;
cout << "File Name: " << fileName << endl;
// Open files stream
ifstream file;
file.open(fileName.c_str());
//Check File Steam
if (file.is_open()) {
// Read arraySize Variable from first line of file
file >> arraySize;
// Create array from arraySize variable; read from file
double sales[arraySize];
// Read data into array
for (int i = 0; i<arraySize; i++) {
file >> sales[i];
}
// Find Total Sales & Average
for (int i = 0; i<arraySize; i++) {
totalSales += sales[i];
}
averageSales = totalSales / arraySize;
//Find largest Sales
for (int i = 0; i<arraySize; i++) {
if (sales[i] > highest) {
highest = sales[i];
}
}
//Find lowest Sales - set default lowest value to the highest value
lowest = highest;
for (int i = 0; i<arraySize; i++) {
if (sales[i] < lowest) {
lowest = sales[i];
}
}
//Close File stream
file.close();
}
else {
cout << "Error Opening File" << endl;
}
//Sort Array
BubbleSort(sales, arraySize);
//Output Sales data
cout << "Total Sales: " << totalSales << endl;
cout << "Average Sales: " << averageSales << endl;
cout << "Highest Sales amount: " << highest << endl;
cout << "Lowest Sales Amount: " << lowest << endl;
//Choice to rerun
cout << endl << "Would you like to run again? Y/N " << endl;
cin >> rerun;
} while (rerun == 'y' || rerun == 'Y');
}
答案 0 :(得分:4)
首先,在sales
- 块中声明变量if
,而在此BubbleSort
- 块之外调用if
。因此,变量超出范围,不能用于调用。
此外,请注意void BubbleSort(int arr[], int n)
需要一个整数数组,而sales
是一个双精度数组,即double sales[arraySize]
。
一旦纠正了范围问题,调用BubbleSort(sales, arraySize)
就会产生编译错误。
答案 1 :(得分:0)
你已经在里面宣布你的阵列&#39;如果&#39;块。它只存在于那里。此外,&#39;销售&#39;是双精度数组,但是你的函数需要一个整数数组。