Pages

Wednesday, 25 April 2018

Chapter 8 // Exercise 9 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


Chapter 8 // Exercise 9



9. Write a function that given two vector<double>s price and weight computes a value (an "index") that is the sum of all price[i]*weight[i]. Make sure to have weight.size()==price.size().


#include "stdafx.h"
#include "std_lib_facilities.h"

//read numbers into weight
vector<double> getAmount(string label)
{
 vector<double> v_amount;
 int howMany;
 double amount;

 cout << "How many items are there for " << label << ": ";
 cin >> howMany;
 for (int i = 0; i < howMany; ++i)
 {
  cout << ">>";
  cin >> amount;
  v_amount.push_back(amount);
  cout << endl;
 }
 
 return v_amount;
}

//multiply weight by price if vectors are same size
double getSum(const vector<double>& price, const vector<double>& weight)
{
 double sum = 0;

 if (price.size() == weight.size())
 {
  for (int i = 0; i < price.size(); ++i)
  {
   sum += price[i] * weight[i];
  }
 }
 else
  cout << "Sorry those vectors are not the same size.\n";

 cout << "\nSum: " << sum << endl;

 return sum;
}


int main()
{
 vector<double> weight = getAmount("weight");
 vector<double> price = getAmount("price");

 double sum = getSum(price, weight);

 keep_window_open();

 return 0;
}

No comments:

Post a Comment