Reputation: 58
I am getting an integer value as my output but i want it to be a float value.I am not able to figure out the problem in my code. Here is the code.
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using std::vector;
using namespace std;
double get_optimal_value(int n, int capacity, vector<int> weights, vector<int> values) {
double value = 0.0,p=0.0;
float max=0.0;
float m=n,i,k,j,t;
// write your code here
vector<double> a(m);
for(i=0;i<m;i++)
{
p=(values[i]/weights[i]);
a.push_back(p);
}
sort(a.begin(), a.end(), greater<double>());
for(j=0;j<m;j++)
{
for(k=0;k<m;k++)
{
if(a[j]==values[k]/weights[k])
{
if(weights[k]<=capacity){
value= value + values[k];
capacity=capacity-weights[k];
if(capacity==0)
{
return value;
}
}else if(weights[k]>capacity){
value=value + a[j]*capacity;
return value;
}
}
}
}
return value;
}
int main() {
int n;
int capacity;
std::cin >> n >> capacity;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++) {
std::cin >> values[i] >> weights[i];
}
double optimal_value = get_optimal_value(n,capacity, weights, values);
std::cout.precision(10);
std::cout << optimal_value << std::endl;
return 0;
}
INPUT
1 10 500 30
output 160
but i want the answer to be a double or a float value and the Expected Output is
166.667
could you guys help me out.
Upvotes: 1
Views: 2610
Reputation: 311068
In expressions like this
p=(values[i]/weights[i]);
or like this
if(a[j]==values[k]/weights[k])
in the right hand side there is used the integer arithmetic.
To get a float result you should cast one of operands to the type double as for example
p = static_cast<double>( values[i] ) / weights[i];
or
if ( a[j] == static_cast<double>( values[k] ) / weights[k] )
Upvotes: 2
Reputation: 777
I looked over your code and I'm pretty sure get_optimal_value
can only return integer values. For instance, the line p=(values[i]/weights[i]);
loses a floating point value. I highly recommend using a debugger to closely follow your program and find out where it went wrong.
Upvotes: 0