0

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.

  • 1
    `values[i]/weights[i]` is always going to be `int` value. [What is the behavior of integer division?](https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division) – Yksisarvinen Mar 30 '20 at 15:16
  • Recommended reading: [Why should I not #include ?](https://stackoverflow.com/q/31816095/5910058) – Jesper Juhl Mar 30 '20 at 15:16
  • Does this answer your question? [What is the behavior of integer division?](https://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division) – Yksisarvinen Mar 30 '20 at 15:17

2 Answers2

2

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] )
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
0

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.

NadavS
  • 728
  • 2
  • 12