该程序应该询问用户一定数量的值然后再次询问用户值,对它们进行排序,然后用户将输入一个值。程序应该搜索这个值,并返回值的位置或告诉用户它不是他给出的列表的一部分。
我使用notepad ++和pocketc ++来运行和编译整个程序然后我转移了一个UNIX编辑器,putty和g ++,这就是我遇到问题的地方。当我使用putty和g ++时,程序编译得很好,但只返回在中间排序的值。例如,我想要3个数字,1 2 3.然后我问程序2是什么,它返回2是在第二个位置,但任何其他数字将给我一个垃圾值。这只适用于putty和c ++,而pocketc ++适用于所有值。
#include <iostream>
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
char answer;
int list,target, first, last;
int *array;
int search(int , int , int , int );
int sort( int a[], int);
int index_of_smallest(const int array[], int first, int target);
void swap(int& v1, int& v2);
int search(int data[], int target, int first, int last);
cout << "How many integers does your list have?\n";
cin >> list;
array = new int[list];
cout << "Please enter your integers: ";
for (int i = 0; i < list; i++)
cin >> array[i];
do {
cout << "\nWhat is the target value?\n";
cin >> target;
sort(array,list);
first = 0;
last = list-1;
int k= search( array, target, first, last);
if (k == -1) cout << "That number is not a part of your list of integers.\n";
else cout << "The location of " << target << " is spot " << k+1 << endl;
cout << "Would you like to search a different number?" << endl;
cin >> answer;
} while (answer !='n' && answer !='N');
return 0;
}
int index_of_smallest(const int array[], int first, int target){
int min= array[first];
int index_min=first;
for ( int i = first + 1; i < target; i++)
if (array[i] < min) {min = array[i];
index_min = i;}
return index_min;
}
void swap(int& v1, int& v2){
int temp;
temp = v1;
v1=v2;
v2=temp;
}
void sort(int a[], int num){
int next_smallest;
for (int i= 0; i < num - 1; i++)
{
next_smallest =index_of_smallest(a, i, num);
swap (a[i],a[next_smallest]);
}
}
int search(int data[], int target, int first, int last) {
int middle;
if (first > last)
return -1;
else {
middle=(first + last)/2;
if (target == data[middle])
return middle;
else if ( target < data[middle])
search(data, target, first, middle-1);
else if (target > data[middle])
search(data, target, middle +1, last);}
}
答案 0 :(得分:2)
在简要查看代码的同时,没有什么特别突出的。话虽这么说,如果我通过编译器运行你的代码,会出现以下警告:
[11:04pm][wlynch@watermelon /tmp] g++ -Wall foo.cc
foo.cc: In function ‘int search(int*, int, int, int)’:
foo.cc:76: warning: control reaches end of non-void function
所以我们看一下搜索功能。看起来你打算让函数递归,所以我相信你应该用更多的return语句编写它:
int search(int data[], int target, int first, int last) {
int middle;
if (first > last)
return -1;
else {
middle=(first + last)/2;
if (target == data[middle])
return middle;
else if ( target < data[middle])
return search(data, target, first, middle-1);
else if (target > data[middle])
return search(data, target, middle +1, last);
}
}