Something is going wrong in my program, it will run, but when I put in any number or character in for an answer, it says it is a correct lottery number.
My program:
#include <iostream>
#include <string>
using namespace std;
int LinearSearch (int [], int, int);
int main()
{
const int Lottery = 10;
int nums [Lottery] = {13579, 26791, 26792, 33445, 55555, 62483, 77777, 79422, 85647, 93121 };
int UserSelection, location;
double USER;
cout << "Type in the lottery number you have purchased now:\n\n ";
cin >> UserSelection;
You need to be more careful with where you put your semicolons.
For example in this code:
Code:
for (x=0; x < size; x++);
{
if (list [x] == key);
return 0;
}
The semicolons after the for and if statements end those statements. So what happens is this:
1) The 'for' loop runs, but does nothing except increment x
2) We go into the curly brackets, and the 'if' statements runs, but does nothing
3) We reach the 'return 0;' line, which returns 0
So the search function will always return 0 whether or not the lottery number is found.
As an aside, if you had run your code through a debugger you would have spotted this straight away.
Any ideas on how to change this as easily as possible from a linear search to a binary ?
The standard library contains std::binary_search (if you just want to check existence) or std::lower_bound (if you want to actually get a handle to the element if it exists).
Whether or not you are allowed to use these in your class is a different matter.
Bookmarks