Arunima Khanna
Arunima Khanna

Reputation: 11

Scaling a float value in c++

I was trying to solve a question on hackerrank in which I am supposed to find weighted mean. But in one particular test case my code is not working.

Test Case: 10          //size of weighted and elements array
10 40 30 50 20 10 40 30 50 20     //elements
1 2 3 4 5 6 7 8 9 10              //respective weights

Expected Output is 31.1

and my answer is coming out to be 31.0

My Code:

#include <algorithm>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;

int calc_weighted_mean(int x[], int w[], int n) {
  float numerator = 0.0, denominator = 0.0;

  for (int i = 0; i < n; i++) {
    numerator += x[i] * w[i];
    denominator += w[i];
  }

  float ans = numerator / denominator;

  round(ans);

  return (ans);
}

int main() {

  int n;
  cin >> n;

  if (n >= 5 && n <= 50) {
    int x[100005], w[100005];

    for (int i = 0; i < n; i++) {
      cin >> x[i];
    }

    for (int i = 0; i < n; i++) {
      cin >> w[i];
    }

    float ans = calc_weighted_mean(x, w, n);
    cout << fixed;
    cout << setprecision(1);
    cout << ans << endl;
  } else {
    cout << -1;
  }
  return 0;
}

Upvotes: 0

Views: 540

Answers (1)

john
john

Reputation: 87952

You've written your calc_weighted_mean function to return an int. So obviously it can never return a value of 31.1.

Change the function to return a float and remove the line that says round(ans); which is doing nothing in any case because you don't capture the return value.

Upvotes: 3

Related Questions