Предмет: Информатика, автор: whatisslove

Есть вот такой код, нужно в него добавить каким либо образом Изготовителя(чтобы в массиве на каждой строке первым было слово и чтобы в общем изготовителей было хотя бы 3 разных) хоть рандомный набор букв, хоть самому записывать, хоть записать варианты и потом сделать рандомный выбор из них, как угодно главное тоже через класс
Даю 50 баллов

#include
#include

const int N=10;

class Commutator
{
public:
int portCounter;
int portSpeed;
int matrixSpeedCommunication;
float price;

Commutator ()
{
};

Commutator (int portCounter_, int portSpeed_, int matrixSpeedCommunication_, float price_)
{
portCounter = portCounter_;
portSpeed = portSpeed_;
matrixSpeedCommunication = matrixSpeedCommunication_;
price = price_;
}
};

int main()
{
srand(time(nullptr));

Commutator commutatorArray[N];
for (int i = 0; i < N; ++i)
{
commutatorArray[i] = *new Commutator (rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, 0);
commutatorArray[i].price = commutatorArray[i].portCounter * 2.0 + commutatorArray[i].matrixSpeedCommunication * 1.5 + commutatorArray[i].portSpeed * 1.2;
std::cout <<"["<< i << "] " << commutatorArray[i].portCounter << "; " << commutatorArray[i].matrixSpeedCommunication << "; " << commutatorArray[i].portSpeed << "; " << commutatorArray[i].price << "\n";
}
Commutator bestPriceArray[N];
Commutator bestPortCounter[N];
std::copy(commutatorArray, commutatorArray+N, bestPriceArray);
std::copy(commutatorArray, commutatorArray+N, bestPortCounter);

//Sort by price
std::sort(bestPriceArray, bestPriceArray+N, [] (const Commutator & a, const Commutator & b) -> bool
{
return a.price > b.price;
});

//Sort by portNumber
std::sort(bestPortCounter, bestPortCounter+N, [] (const Commutator & a, const Commutator & b) -> bool
{
return a.portCounter < b.portCounter;
});

std::cout<<"Best price:\n";
for (int i = 1; i < 6; ++i)
{
std::cout << "[" << i << "] " << bestPriceArray[N-i].portCounter << "; " << bestPriceArray[N-i].matrixSpeedCommunication << "; " << bestPriceArray[N-i].portSpeed << "; " << bestPriceArray[N-i].price << "\n";
}
std::cout<<"Best port counter:\n";
for (int i = 1; i < 6; ++i)
{
std::cout << "[" << i << "] " << bestPortCounter[N-i].portCounter << "; " << bestPortCounter[N-i].matrixSpeedCommunication << "; " << bestPortCounter[N-i].portSpeed << "; " << bestPortCounter[N-i].price << "\n";
}
}​

Ответы

Автор ответа: honvert
1

Ответ:

Чтобы добавить изготовителя в класс Commutator, вам нужно создать новое поле в классе с именем manufacturer и типом std::string, а затем инициализировать его в конструкторе:

class Commutator

{

public:

int portCounter;

int portSpeed;

int matrixSpeedCommunication;

float price;

std::string manufacturer; // Добавляем новое поле

Commutator ()

{

};

Commutator (int portCounter_, int portSpeed_, int matrixSpeedCommunication_, float price_, std::string manufacturer_) // Добавляем новый параметр в конструктор

{

portCounter = portCounter_;

portSpeed = portSpeed_;

matrixSpeedCommunication = matrixSpeedCommunication_;

price = price_;

manufacturer = manufacturer_; // Инициализируем поле

}

};

Теперь вы можете использовать это поле для хранения изготовителя в каждом экземпляре класса. Например, чтобы создать экземпляр с рандомным изготовителем, вы можете сгенерировать случайную строку и передать ее в конструктор:

Commutator commutatorArray[N];

for (int i = 0; i < N; ++i)

{

   std::string manufacturer = "Manufacturer " + std::to_string(rand() % 3 + 1); // Генерируем случайный изготовитель

   commutatorArray[i] = *new Commutator (rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, 0, manufacturer);

   commutatorArray[i].price = commutatorArray[i].portCounter * 2.0 + commutatorArray[i].matrixSpeedCommunication * 1.5 + commutatorArray[i].portSpeed * 1.2;

std::cout <<"["<< i << "] " << commutatorArray[i].portCounter << "; " << commutatorArray[i].matrixSpeedCommunication << "; " << commutatorArray[i].portSpeed << "; " << commutatorArray[i].price << "; " << commutatorArray[i].manufacturer << "\n"; // Выводим изготовителя

}

Или же вы можете создать массив строк с вариантами изготовителей и выбирать из них случайно:

std::string manufacturers[] = {"Manufacturer 1", "Manufacturer 2", "Manufacturer 3"};

Commutator commutatorArray[N];

for (int i = 0; i < N; ++i)

{

   std::string manufacturer = manufacturers[rand() % 3]; // Выбираем случайный изготовитель из массива

   commutatorArray[i] = *new Commutator (rand() % 20 + 5, rand() % 4000 + 2000, rand() % 100 + 20, 0, manufacturer);

   commutatorArray[i].price = commutatorArray[i].portCounter * 2.0 + commutatorArray[i].matrixSpeedCommunication * 1.5 + commutatorArray[i].portSpeed * 1.2;

   std::cout <<"["<< i << "] " << commutatorArray[i].portCounter << "; " << commutatorArray[i].matrixSpeedCommunication << "; " << commutatorArray[i].portSpeed << "; " << commutatorArray[i].price << "; " << commutatorArray[i].manufacturer << "\n";

}

Похожие вопросы
Предмет: Литература, автор: ilyameridianoff
Текст М. Енде « Джим Ґудзик і машиніст Лукас»
Треба написати Так чи Ні
Даю 25 балов

1. Лукас жив у маленькій країні Усландія.
2. Лукас жив у маленькій будівлі біля підніжжя гори
3. Острів лежав посеред безкрайнього океану.
4. Особистий локомотив Лукаса звали Енні.
5. У Лукаса були карі очі.
6. Лукас був пречудовим майстром стріляти з рогатки.
7. Хлопець умів плювати петле подібно
8. На острові було 5 тунелів.
9. Короля звали Альфонс За-Чверть-Дванадцять.
10. Щоки пані Ваас були схожі на дві морквини.
11. Пані Ваас жила в будинку,де знаходилася крамниця.
12. В крамниці продавалося все.
13. Короля можна було побачити кожний день.
14. Король у святкові дні пригощав своїх підданих морозивом.
15. Майстринею приготування морозива була пані Ваас.
16. Одного дня до берега Усландії прибув поїзд.
17. У посилці було темношкіре немовля.
18. Пані Ваас дуже зраділа, бо їй завжди хотілося мати малюка.
19. Хлопчика назвали Джупітер.
20. Коли приїхав знову поштар, пані Ваас злякалася, що заберуть Джима.
21. Найкращим другом Джима був Лукас – машиніст.
22. Джим дуже хотів стати машиністом.
Предмет: Английский язык, автор: epigames