Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

C++ std::accumulate doesn't give the expected sum

double numbers[ ] = { 1, 0.5 ,0.333333 ,0.25 ,0.2, 0.166667, 0.142857, 0.125,
                       0.111111, 0.1 } ;
std::vector<double> doublenumbers ( numbers , numbers + 10 ) ;
std::cout << std::accumulate ( doublenumbers.begin( ) , doublenumbers.end( ) , 0 ) ;

This produces 1, which is evidently wrong. Any explanations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should write the following:

std::cout << 
 std::accumulate ( doublenumbers.begin( ) , doublenumbers.end( ) , 0.0 ) ;

Because the type of 0 is int.

When std::accumulate is instantiated with the type of the third argument is int, then it would convert the right hand side of the sum. e.g.:

   result += *iter;
// int    += double

This would force a conversion of double to int, instead of what you were thinking of which is the opposite.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...