std::accumulate

This is a discussion on std::accumulate within the C++ Programming forums, part of the General Programming Boards category; I have a problem with this std::accumulate function. When compiling this I have quite much compile notifications but it compiles. ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    383

    std::accumulate

    I have a problem with this std::accumulate function. When compiling this I have quite much compile notifications but it compiles.
    One that says:

    warning C4244: '=' : conversion from 'double' to 'int', possible loss of data

    This is what is happening here. I have declared the elements in vector "vec" to doubles with 2 decimals.
    However the output of this will be 15 wich is an integer. The output should have been. (10,50 + 20,50 / 2) = 15,50.

    I wonder what I could be doing wrong since everything is declared to doubles. Where is the conversion from double to int that seems to be happening.


    Code:
    #include <numeric>
    
    std::vector<double> vec(12);
    
    vec[1] = 10.50;
    vec[2] = 20.50;
    
    double sum = std::accumulate( vec.begin() + 1, vec.begin() + 3, 0);
    double Average = ( sum / (3 - 1)  );
    			
    ofstream out;
    out.open("C:\\test.txt");
    
    out << Average
    Last edited by Coding; 03-16-2008 at 05:44 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,588
    The function template determine the type based on the initial value. 0 is an int literal, 0.0 is a double literal, so if you want to instantiate std::accumulate<double>, you would write:
    Code:
    double sum = std::accumulate(vec.begin() + 1, vec.begin() + 3, 0.0);
    EDIT:
    Actually, it's not std::accumulate<double>, but effectively std::accumulate<std::vector<double>::iterator, double>.
    Last edited by laserlight; 03-16-2008 at 06:04 PM.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    383
    okay, that was the thing... It worked fine.
    thanks..

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. std::accumulate with double type
    By cunnus88 in forum C++ Programming
    Replies: 8
    Last Post: 10-25-2006, 12:23 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21