我的代码完成并正常运行。但我无法弄清楚如何计算用户的尝试次数和输入的无效帐号。我应该在cin>>之后的主要开始时这样做accountNum。用户输入9999退出后,应显示已尝试的次数和输入的无效收费帐号的数量。当我运行它时,我的尝试次数为0,输入的无效数字为-1。
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
void getAccountNumbers(int[], int);
void displayAccountNumbers(int[], int);
void selectionSort(int[], int);
int binarySearch(const int[], int, int);
int main()
{
int accountNum;
int results;
int attempts = 0;
int invalidNumbers = 0;
const int ARRAY_SIZE = 18; // Array size
int numbers[ARRAY_SIZE]; // Array with 18 elements
int count = 0;
//ifstream inputFile;
getAccountNumbers(numbers, ARRAY_SIZE);
cout << "Original Order" << endl;
displayAccountNumbers(numbers, ARRAY_SIZE);
selectionSort(numbers, ARRAY_SIZE);
cout << "Sorted List" << endl;
displayAccountNumbers(numbers, ARRAY_SIZE);
cout << "********************" << endl;
cout << "Enter an Account number or 9999 to quit" << endl;
cin >> accountNum;
if(accountNum == 9999)
{
cout << "Thank You!" << endl;
}
while(accountNum != 9999)
{
results = binarySearch(numbers, ARRAY_SIZE, accountNum);
if(results == -1)
{
cout << "That number was not found" << endl;
invalidNumbers = results++;
}
else
{
cout << "That number is valid " << endl;
}
attempts = results++;
cin >> accountNum;
}
cout << "Number of attempts: " << attempts << endl;
cout << "Invalid numbers entered: " << invalidNumbers << endl;
system("pause");
return 0;
}
void getAccountNumbers(int nums[], int size)
{
ifstream inputFile;
int count = 0;
//Open the file
inputFile.open("charges.txt");
while(count < size && inputFile >> nums[count])
count ++;
//Close the file
inputFile.close();
}
void displayAccountNumbers(int nums[], int size)
{
for(int count = 0; count < size; count++)
cout << nums[count] << "\t";
cout << endl << endl;
}
void selectionSort(int nums[], int size)
{
int startScan, minIndex, minValue;
for(startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minValue = nums[startScan];
for(int index = startScan + 1; index < size; index++)
{
if(nums[index] < minValue)
{
minValue = nums[index];
minIndex = index;
}
}
nums[minIndex] = nums[startScan];
nums[startScan] = minValue;
}
}
int binarySearch(const int nums[], int size, int value)
{
int first = 0, //First element
last = size - 1, // Last element
middle, // Midpoint
position = -1; //Position of search value
bool found = false;
while(!found && first <= last)
{
middle = (first + last) / 2; //Midpoint
if(nums[middle] == value)
{
found = true;
position = middle;
}
else if(nums[middle] > value) // Value is in lower half
last = middle - 1;
else
first = middle + 1; // Value is in upper half
}
return position;
}
答案 0 :(得分:1)
您的问题出在您尝试添加到invalidNumbers
和attempts
的行中。 ++ postfix运算符在它之前的数字中加一。你不必说invalidNumbers = results++;
;您只需要invalidNumbers++;
,同样适用于attempts
。您的代码正在做的是将invalidNumbers
(和attempts
)设置为results
的值,然后将{1}}添加到results
。