How to find sum in c++

下次还敢
Release: 2024-04-28 18:06:17
Original
617 people have browsed it

Several ways to sum in C include: Built-in function std::accumulate(): Calculates the sum of a series of values. Built-in function sum(): Short for accumulate(), takes a container as input. Container method std::vector::accumulate(): Specially used for std::vector containers. Container method std::vector::sum(): Returns the sum of all elements in the container.

How to find sum in c++

How to sum in C

C provides a variety of built-in functions and container methods to calculate arrays and vectors Or the sum of the elements in the list.

Built-in function

  • accumulate(): Used to calculate the sum of a series of values. It accepts an iterator range and an optional initial value, and returns the sum.
#include  #include  int main() { int arr[] = {1, 3, 5, 7, 9}; int sum = std::accumulate(arr, arr + 5, 0); std::cout << "总和为:" << sum << std::endl; return 0; }
Copy after login
  • sum(): This is the abbreviated version ofaccumulate()which takes a container as input and returns the sum.
#include  int main() { std::vector vec = {1, 3, 5, 7, 9}; int sum = std::sum(vec); std::cout << "总和为:" << sum << std::endl; return 0; }
Copy after login

Container methods

  • std::vector::accumulate(): Similar tostd: :accumulate(), but designed specifically forstd::vectorcontainers.
  • std::vector::sum(): Returns the sum of all elements in the container, similar tostd::sum().

Example

#include  int main() { std::vector vec = {1, 3, 5, 7, 9}; int sum = std::accumulate(vec.begin(), vec.end(), 0); std::cout << "总和为:" << sum << std::endl; return 0; }
Copy after login

Notes

  • For very large or very small sizes that may produce overflow numbers, consider usinglong longor other large integer types.
  • For an empty container or range, the sum function returns the initial value (usually 0).

The above is the detailed content of How to find sum in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c++
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!