Calculate Radio Costs Using Matrix Multiplication
% cat radioMat.cpp
// Matrix multiply problem - radio type
#include <iostream>
#include <iomanip>
using namespace std;
const int MAX=5;
void matMult(int A[][MAX], double B[][MAX],
double C[][MAX], int rowsA, int colsA,
int rowsB, int colsB, int &rowsC,
int &colsC);
int main()
{
int i, j, ntype, ncomp, rowsC, colsC;
int comp[MAX][MAX];
double cost[MAX][MAX] ;
double radio[MAX][MAX];
cout << "Enter the number of radio types: ";
cin >> ntype;
cout << "Enter the number of components: ";
cin >> ncomp;
// input component data
cout << "For each type, enter the number of
capacitors,
resistors, and transistors\n";
for (i = 0; i < ntype; i++)
for (j = 0; j < ncomp; j++)
cin >> comp[i][j];
cout << "Enter the cost of capacitors,
resistors,
and transistors: ";
cin >> cost[0][0] >> cost[1][0] >>
cost[2][0];
// call matrix multiply routine to calculate radio
costs
matMult( comp, cost, radio, ntype, ncomp, ncomp, 1,
rowsC, colsC);
// display results
cout << setiosflags(ios::showpoint |
ios::fixed)
<< setprecision(2);
for(i = 0; i < ntype; i++)
cout << "Radio type " << i+1
<< " costs $" << radio[i][0] << endl;
return 0;
}
// matrix multiply function
void matMult(int A[][MAX], double B[][MAX],
double C[][MAX], int rowsA, int colsA,
int rowsB, int colsB, int &rowsC,
int &colsC)
{
int i, j, k;
if(colsA != rowsB)
{
cout << "Error: cols A must = rows B/n";
exit(1);
}
rowsC = rowsA;
colsC = colsB;
for(i = 0; i < rowsA; i++)
for(j = 0; j < colsB; j++)
{
C[i][j] = 0.0;
for(k=0; k < colsA; k++)
C[i][j]
+= A[i][k] * B[k][j];
}
return;
}
% g++ radioMat.cpp
% a.out
Enter the number of radio types: 4
Enter the number of components: 3
For each type, enter the number of capacitors, resistors, and
transistors
2 6 3
6 11 5
13 29 10
8 14 7
Enter the cost of capacitors, resistors, and transistors: .35 .2
1.40
Radio type 1 costs $6.10
Radio type 2 costs $11.30
Radio type 3 costs $24.35
Radio type 4 costs $15.40
|