Search code examples
c++syntaxstatisticstype-conversionweighted-average

Why am I not able to print 32.0 instead of 32 inspite of typeconversion?


So Here's my code. the inputs are

5

10 40 30 50 20

1 2 3 4 5

I'm trying to find the weighted mean of an array of size n, vector a holding the n elements with their corresponding weights in vector b. I'm unable to understand why 32 is being printed out instead of 32.0? Can someone tell me why and how I can change it?

int main() {
    int n;
    cin>>n;
    vector<int> a(n),b(n);
    for(int i=0;i<n;i++){
        cin>> a[i] ;
    }
    for(int i=0;i<n;i++){
        cin>> b[i] ;
    }
    double s=0,w=0;
    for(int i=0;i<n;i++){
        s+=b[i]*a[i];
        w+=b[i];
    }
    cout<<s/w*1.0;

    return 0;
}

Solution

  • Whether it prints 32 or 32.0 is a subject of output formatting. By default, it clips all unnecessary digits (and the decimal point as well) if possible. (The *1.0 doesn't help for this.)

    The relevant functions are available in <iomanip>:

    Example:

    #include <iomanip>
    #include <iostream>
    
    int main()
    {
      std::cout
        << 32.0 << '\n'
        << std::fixed << std::setprecision(1) << 32.0 << '\n';
    }
    

    Output:

    32
    32.0
    

    Live Demo on coliru