gpt4 book ai didi

c++ - 为什么我的程序在使用不同的编辑器和编译器时表现不同?

转载 作者:行者123 更新时间:2023-11-30 04:18:23 25 4
gpt4 key购买 nike

<分区>

这个程序应该向用户询问一组值,然后再次向用户询问这些值,对它们进行排序,然后用户将输入一个值。该程序应该搜索此值并返回该值的位置或告诉用户它不在他提供的列表中。

我使用 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);}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com