【发布时间】:2019-05-15 20:53:27
【问题描述】:
我正在编写一个程序,以确定 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;
}
【问题讨论】:
-
您好 Neo J。欢迎来到 SO。你知道
struct吗? -
我目前正在第一次进行调查......任何见解将不胜感激。谢谢!
-
你为什么不试试上课呢?作为 c++,您可以拥有一个带有多个参数(名称、成本、年份等)的船类,并且主要创建 5 个船对象,实例化参数并调用该类的函数!
-
“我想给每艘船命名,并输出最低的运营成本和它对应的船名”——好的,你有什么问题?
-
既然你是初学者,让我先告诉你,你的程序找到了解决方案,但不是以最好的方式。您应该just 查找最小值,而不是按值对数组进行排序(如果您理解这部分,请告诉我)。但是使用您的方法仍然可以打印船的名称。 1) 创建一个名称数组,2) 创建一个
swapName函数,您每次调用swap时都会调用该函数和 3)在cout<<"Your lowest ...的末尾添加名称的输出。这对你有意义吗??
标签: c++ arrays multidimensional-array data-structures types