C ++: типы данных и массивы - PullRequest
       17

C ++: типы данных и массивы

0 голосов
/ 14 декабря 2018

Я кодирую программу, которая определяет самую низкую стоимость эксплуатации из 5 названных лодок.Это рассчитывается с использованием заранее определенных целых чисел, хранящихся в массивах, вместе с пользовательскими входными целыми числами.Я смог завершить программу, но я хочу назвать каждую лодку и вывести самую низкую стоимость эксплуатации с соответствующим названием лодки.Любое понимание приветствуется!Спасибо и извините за мой неаккуратный код, я новичок в этом.

#include <string>
#include <iostream>
#include <stdio.h> 
using namespace std;


   void swap(int *xp, int *yp) 
{ 
    int temp = *xp; 
    *xp = *yp; 
    *yp = temp; 
} 

void bubbleSort(int arr[], int n) 
{ 
   int i, j; 
   for (i = 0; i < n-1; i++)       

       for (j = 0; j < n-i-1; j++)  
           if (arr[j] > arr[j+1]) 
              swap(&arr[j], &arr[j+1]); 
} 

void printArray(int arr[], int size) 
{ 
    int i; 
    for (i=0; i < size; i++) 
        printf("%d ", arr[i]); 
        cout<<"\n";
     }


int main()
{

//Declarations

int numBoats = 5;

int boatData[5];

int costGas;

int yearsService;

int i;

int j;

int boatArray[5][3] = {{30, 100, 5000}, 
                     {20, 200, 10000}, 
                     {30, 200, 2000}, 
                     {25, 150, 12000}, 
                     {30, 50, 8000}};

//User input 

cout << "Please enter the first boats cost of gas: "<<endl;
cin >> costGas;
cout << "The cost of gas you entered is " << costGas << endl;

cout << "Please enter the number of years in service: " << endl;
cin >> yearsService;
cout << "The number of years in service you entered is " << yearsService << endl;

//Calculations

for (i = 0; i < numBoats; i++) {

int mpg = boatArray[i][1];
int maintenanceCost = boatArray[i][2]; 
int purchaseCost = boatArray[i][3];

int totalMiles = 15000 * yearsService;
int gasTotal = totalMiles / mpg;
int maintenanceTotal = maintenanceCost * yearsService;
int operatingCost = purchaseCost + gasTotal + maintenanceTotal;

boatData[i] = operatingCost;
}

//Print operating costs

 cout<<"The operating costs of each boat is: "<<endl;

printArray(boatData, numBoats);

//Bubblesort

bubbleSort(boatData, numBoats); 
printArray(boatData, numBoats);

cout<<"Your lowest operating cost is "<<boatData[0]<<endl;

    return 0;
}

Ответы [ 2 ]

0 голосов
/ 14 декабря 2018

Я бы просто добавил некоторый справочный массив с уникальными номерами для лодок и отсортировал бы их вместе со значениями.Функция сортировки:

void bubbleSort (int id[], int arr[], int n) 
{ 
int i, j; 
for (i = 0;  i < n - 1;  i++)
    for (j = 0;  j < n - i - 1;  j++)  
        if  ( arr[j] > arr[j+1] ) {
            swap ( arr[j], arr[j+1] ); 
            swap ( id[j], id[j+1] ); 
        }
}

Затем я обращаюсь к именам по этим отсортированным идентификаторам.
Этот упрощенный пример показывает, как это может применяться к вашему случаю, он печатает некоторые данные (здесь имена) до и после сортировки:

int main () 
{

const int n = 5;
int     boatID[n] = { 0, 1, 2, 3, 4 };
string  name[n] = { "oak", "pine", "maple", "cypress", "elm" };
int     value[n] = { 20, 10, 0, 25, 15 };

for (int i = 0; i < n; i++) 
    cout << "id: " << boatID[i] << "  value: " << value[i] << "  name: " << name[boatID[i]] << endl;

bubbleSort (boatID, value, n);  // sort references by value

cout << "* sorted *" << endl;
for (int i = 0; i < n; i++) 
    cout << "id: " << boatID[i]  << "  value: " << value[i] << "  name: " << name[boatID[i]] << endl;

} 

Обратите внимание, что вместо вывода индекса name[] используется boatID[i].

0 голосов
/ 14 декабря 2018

Это то, что я сделаю, чтобы найти самые низкие операционные затраты:

#include <string>
#include <iostream>
#include <stdio.h> 
using namespace std;


int NUM_BOATS = 5;

struct Boat {
  int mpg;
  int maintenanceCost;
  int purchaseCost;
  string name;
  int operatingCost; // total of your calculation
};

void caculation(Boat& boat, int yearsService){
  int totalMiles = 15000 * yearsService;
  int gasTotal = totalMiles / boat.mpg;
  int maintenanceTotal = boat.maintenanceCost * yearsService;
  boat.operatingCost = boat.purchaseCost + gasTotal + maintenanceTotal;
}

void print(Boat& boat){
  cout << "mpg: " << boat.mpg << endl;
  cout << "maintenanceCost: " << boat.maintenanceCost << endl;
  cout << "purchaseCost: " << boat.purchaseCost << endl;
  cout << "name: " << boat.name << endl;
  cout << "operatingCost: " << boat.operatingCost << endl;
}

int main()
{
  Boat BoatData[5] = { {30, 100, 5000, "Boat a", 0},
                       {20, 110, 5500, "Boat b", 0},
                       {35, 120, 4000, "Boat c", 0},
                       {10, 300, 1000, "Boat d", 0},
                       {40, 200, 3000, "Boat e", 0},
                      } ;
  //User input 
  int costGas;
  cout << "Please enter the first Boats cost of gas: "<<endl;
  cin >> costGas;
  cout << "The cost of gas you entered is " << costGas << endl;
  int yearsService;
  cout << "Please enter the number of years in service: " << endl;
  cin >> yearsService;
  cout << "The number of years in service you entered is " << yearsService << endl;

  int iMin = 0;
  int minCost = 99000; // a really high number

  for(int i=0; i<NUM_BOATS; ++i){
    print(BoatData[i]);
    caculation(BoatData[i], yearsService);  // calculate all your operatingCost
    if (BoatData[i].operatingCost < minCost){  // and check if is the lowest operatingCost
      iMin = i;      // if it is, save that index
    }
  }

  cout << "Your lowest operating cost is " << BoatData[iMin].operatingCost << " with the boat " << BoatData[iMin].name << endl;

  return 0;
}

Но исходя из вашего кода и ваших комментариев, ваш подход заключается в сортировке массива, так что это то, что вы должны реализовать вВаш код:

#include <string>
#include <iostream>
#include <stdio.h> 
using namespace std;


void swap(int *xp, int *yp) 
{ 
    int temp = *xp; 
    *xp = *yp; 
    *yp = temp; 
} 

void swapName(string& x, string& y) 
{ 
    string temp(x); 
    x = y; 
    y = temp; 
} 

void bubbleSort(int arr[], string boatName[], int n) 
{ 
   int i, j; 
   for (i = 0; i < n-1; i++)       

       for (j = 0; j < n-i-1; j++)  
           if (arr[j] > arr[j+1])
           { 
              swap(&arr[j], &arr[j+1]);              // if you have to swap the data
              swapName(boatName[j], boatName[j+1]);  // swap also the names
           }
} 

void printArray(int arr[], int size) 
{ 
    int i; 
    for (i=0; i < size; i++) 
        printf("%d ", arr[i]); 
}


int main()
{
  //Declarations
  int numBoats = 5;
  int boatData[5];
  string boatName[5] = {"a", "gg", "tt", "hh", "jj"};//
  int costGas;
  int i;
  int j;
  int boatArray[5][3] = {{30, 100, 5000}, 
                       {20, 200, 10000}, 
                       {30, 200, 2000}, 
                       {25, 150, 12000}, 
                       {30, 50, 8000}};

  //User input 
  cout << "Please enter the first boats cost of gas: "<<endl;
  cin >> costGas;
  cout << "The cost of gas you entered is " << costGas << endl;
  int yearsService;
  cout << "Please enter the number of years in service: " << endl;
  cin >> yearsService;
  cout << "The number of years in service you entered is " << yearsService << endl;

  //Calculations
  for (i = 0; i < numBoats; i++) {
    int mpg = boatArray[i][1];
    int maintenanceCost = boatArray[i][2]; 
    int purchaseCost = boatArray[i][3];

    int totalMiles = 15000 * yearsService;
    int gasTotal = totalMiles / mpg;
    int maintenanceTotal = maintenanceCost * yearsService;
    int operatingCost = purchaseCost + gasTotal + maintenanceTotal;

    boatData[i] = operatingCost;
  }

  //Print operating costs
   cout<<"The operating costs of each boat is: "<<endl;
  printArray(boatData, numBoats);

  //Bubblesort
  bubbleSort(boatData, boatName, numBoats);  // pass also the name's array
  printArray(boatData, numBoats);

  cout<<"Your lowest operating cost is "<<boatData[0]<< " with the boat " << boatName[0] << endl;  // print the name

  return 0;
}
...