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;
double weight;
double price;
double m;
} item;

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.name,"Item No.1");
cout << item.name << endl;
cout << "Weight: ";
cin >> item.weight;
cout << "Price: ";
cin >> item.price;
cout << endl;

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

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

strcpy_s(item.name,"Item No.4");
cout << item.name << endl;
cout << "Weight: ";
cin >> item.weight;
cout << "Price: ";
cin >> item.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;
}
``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.