Я создал структуру и создал функции для выполнения нескольких вещей на ней. У меня возникают проблемы с функцией sortLength, потому что когда я запускаю программу, сортируются только данные в длине. Все остальное отлично работает, хотя мне интересно, нормально ли, что мой заказ немного с тех пор, как я использую массивы, которые начинают отсчет в 0. Я попросил моего профессора разъяснить, и он сказал мне, если у меня есть (длина, а затем ширина) в массиве и с помощью запятой, чтобы четко отделить ихВвод данных в и сортировка структуры
10,8 4,3 6,5 5,1 2,1 3, 2
тогда он сортируется по длине, то массив будет:
2 ,1 3,2 4, 3 5,1 6,5 10,8
Однако, я не получаю, что для моего выхода. Вот результат, который я получаю.
Вот инструкции для функции sortLength.
Обратите внимание, что функция будет сортировать, используя значение длины каждого прямоугольника (в порядке возрастания).
Выбирайте любой используемый алгоритм; пузырь, выбор или вставка.
Помните, что сортировка по массиву!
#include "stdafx.h"
#include <iostream>
using namespace std;
struct RECTANGLE
{
int length;
int width;
int area;
};
const int SIZE = 4;
// Function prototypes
void getValues(RECTANGLE[]);
void print(RECTANGLE[]);
int findMaxArea(RECTANGLE[]);
void sortLength(RECTANGLE[]);
int main()
{
RECTANGLE arrRect[SIZE];
//an array of type RECTANGLE
int whereMax; //where find max area
//put values to each element of array
getValues(arrRect);
cout << endl << endl;
//print out each element of array
print(arrRect);
whereMax = findMaxArea(arrRect);
//find where max area is
cout << endl;
cout << "Max area is " << arrRect[whereMax].area << " at position " << whereMax;
cout << endl;
sortLength(arrRect); //sort base on Length
cout << endl;
//print out each element of array
print(arrRect);
return 0;
}
/**
* Pre-Condition: This function accepts an array of type RECTANGLE.
* Post-Condition: It prompts the user for a length and width value
* and calculates the area.
*/
void getValues(RECTANGLE arrRect[])
{
//put values to each element of array
for (int i = 0; i<SIZE; i++)
{
cout << "\nEnter length and width : ";
cin >> arrRect[i].length >> arrRect[i].width;
arrRect[i].area = arrRect[i].length * arrRect[i].width;
//calculate area
}
}
/**
* Pre-Condition: This function accepts an array of type RECTANGLE.
* Post-Condition: It prints the data for length, width, and area.
*/
void print(RECTANGLE arrRect[])
{
//print out each element of array
cout << "Length Width Area" << endl;
for (int i = 0; i<SIZE; i++)
{
cout << arrRect[i].length << "\t\t" << arrRect[i].width << "\t"
<< arrRect[i].area << endl;
}
}
/**
* Pre-Condition: This function accepts an array of type RECTANGLE.
* Post-Condition: It returns an int which represents the position
* of the highest area in the data.
*/
int findMaxArea(RECTANGLE arrRect[])
{
int maxIndex = 0;
int max = arrRect[0].area;
for (int i = 0; i<SIZE; i++)
{
if (max < arrRect[i].area)
{
max = arrRect[i].area;
maxIndex = i;
}
}
return maxIndex;
}
/**
* Pre-Condition: This function accepts an array of type RECTANGLE.
* Post-Condition: It sorts the data in the array according to the
* length value.
*/
void sortLength(RECTANGLE arrRect[])
{
int temp;
for (int i = 0; i < (SIZE - 1); i++)
{
for (int j = i + 1; j < SIZE; j++)
{
if (arrRect[i].length > arrRect[j].length)
{
temp = arrRect[i].length;
arrRect[i].length = arrRect[j].length;
arrRect[j].length = temp;
}
}
}
}
Я полагаю, это связано с тем, что вы меняете длину прямоугольников, а не весь прямоугольник – Rulisp