not sure where to post this but anyways I wrote this code to calculate the max profit from a 5 kg max weight.
heres the code. there is an error with the price. when I use small values below 20 its all normal but when
I input large values there is an error with the value.

#include<iostream>
#include<algorithm>
#include<string.h>

using namespace std;
double result;
double capacity = 5;
int NumberOfItems;
int number;

struct items
{
    char name[32];
    double weight;
    double price;
    double m;
} item[256];

bool cmp(items a,items b)
{
    return a.price/a.weight > b.price/b.weight; // the compare function for the sorting algorithm
}

int main()
{
    cout << "Item List" << endl;
NumberOfItems=4;
strcpy_s(item[1].name,"Item No.1");
    cout << item[1].name << endl;
    cout << "Weight: ";
        cin >> item[1].weight;
    cout << "Price: ";
        cin >> item[1].price;
    cout << endl;

strcpy_s(item[2].name,"Item No.2");
    cout << item[2].name << endl;
    cout << "Weight: ";
        cin >> item[2].weight;
    cout << "Price: ";
        cin >> item[2].price;
    cout << endl;

strcpy_s(item[3].name,"Item No.3");
    cout << item[3].name << endl;
    cout << "Weight: ";
        cin >> item[3].weight;
    cout << "Price: ";
        cin >> item[3].price;
    cout << endl;

strcpy_s(item[4].name,"Item No.4");
    cout << item[4].name << endl;
    cout << "Weight: ";
        cin >> item[4].weight;
    cout << "Price: ";
        cin >> item[4].price;
    cout << endl;


sort(item+1,item+NumberOfItems+1,cmp); // Introsort from STL

 number = 1;
 while(capacity>0 && number <= NumberOfItems)
 {
  if(item[number].weight <= capacity)
    {
        result+=item[number].price;
        capacity-=item[number].weight;
        item[number].m=1;
    }
  else
  {
      result+=(item[number].price)*(capacity/item[number].weight);
      item[number].m=(capacity/item[number].weight);
      capacity=0;

  }
  ++number;
 }

cout<<"Total Value = "<<result<<'\n';
cout<<"Total Weight = "<<(double)5-capacity<<'\n';
cout<<"Items Used:\n";
for(int i=1;i<=NumberOfItems;++i)
    if(item[i].m)
    {
       cout<<"We took "<<item[i].m*item[i].weight<<"kg of \""<<item[i].name<<"\" and the value it brought is "<<item[i].price*item[i].m<<"\n";
    }


system("pause");
return 0;
}
This article has been dead for over six months. Start a new discussion instead.