-1
텍스트 파일 (21 12 44 21 -5 63 0)의 숫자를 배열로 읽어 들이고 버블 정렬을 내림차순으로 정렬하는 프로그램을 작성하려고합니다. 양수 만 인쇄합니다. 나는 잠시 동안 노력했지만 표시되는 것은 내가 기대하는 바가 아니다. 텍스트 파일의파일에서 임의의 숫자 읽기 및 버블 정렬
내용은 다음과 같습니다
21 12 44 21 -5 63 0
전체 코드 :
4277075694
1
4261281277
2880154539
2880154539
4277075694
0
내가 잘못하고있는 무슨 :
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <conio.h>
using namespace std;
class bubble
{
public:
unsigned* arr;
int n;
//Constructor
bubble(const int& size) : n(size) { this->arr = new unsigned[n]; }
//function to read from file
void inputvf(istream &f)
{
//check if file is open
if (f.fail()) {
cout << "\n Error in openning file!!!";
exit(1);
}
for (int i = 0; i < n; i++)
f >> arr[i];
delete[] arr;
//close file
//f.close();
}
//Bubble sort function
void bubblesort()
{
for (int i = 1; i<n; i++)//for n-1 passes
{
for (int j = 0; j<n - 1; j++)
{
if (arr[j] < arr[j + 1])
{
int temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void display()
{
cout << endl;
cout << "----------------------\n";
cout << "Sorted array elements \n";
cout << "----------------------\n";
if (arr >= 0){
for (int j = 0; j < n; j++)
cout << arr[j] << endl;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
bubble list(7);
ifstream file("Text.txt");
list.inputvf(file);
list.bubblesort();
list.display();
_getch();
return 0;
결과 내가 코드를 실행 한 후? ??
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <conio.h>
using namespace std;
class bubble
{
public:
//Array of integers to hold values
int* arr;
//Number of elements in array
int n;
//Constructor
bubble(const int& size) : n(size) { this->arr = new int[n]; }
//function to read from file
void inputvf(istream &f)
{
//check if file is open
if (f.fail()) {
cout << "\n Error in openning file!!!";
exit(1);
}
for (int i = 0; i < n; i++)
f >> arr[i];
//delete[] arr;
//close file
//f.close();
}
//Bubble sort function
void bubblesort()
{
for (int i = 1; i<n; i++)//for n-1 passes
{
for (int j = 0; j<n - 1; j++)
{
if (arr[j] < arr[j + 1])
{
int temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void display()
{
cout << endl;
cout << "----------------------\n";
cout << "Sorted array elements \n";
cout << "----------------------\n";
if (arr >= 0){
for (int j = 0; j < n; j++)
cout << arr[j] << endl;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
bubble list(7);
ifstream file("Text.txt");
list.inputvf(file);
list.bubblesort();
list.display();
_getch();
return 0;
}
감사합니다. 나는 당신이 쓴 것을 시도했지만, 여전히 틀렸고 지금은 단지 큰 음수입니다. – Flexmatrix
저에게 효과적이었습니다 - 새 코드를 게시 할 수 있습니까? –