Given a vector of double like: vector<double> dollars Write code that will sum a
ID: 3838026 • Letter: G
Question
Given a vector of double like:vector<double> dollars
Write code that will sum all of the values in the vector. Your code must work for no matter how many elements are in the vector. Also, print the total value just once like:
The total money in the bank is $xx.xx.
Where xx.xx is the actual total calculated. Do not worry about formatting to two decimal places, just output the answer. You may want to add some test values to the vector, but I am more concerned with the code Given a vector of double like:
vector<double> dollars
Write code that will sum all of the values in the vector. Your code must work for no matter how many elements are in the vector. Also, print the total value just once like:
The total money in the bank is $xx.xx.
Where xx.xx is the actual total calculated. Do not worry about formatting to two decimal places, just output the answer. You may want to add some test values to the vector, but I am more concerned with the code Given a vector of double like:
vector<double> dollars
Write code that will sum all of the values in the vector. Your code must work for no matter how many elements are in the vector. Also, print the total value just once like:
The total money in the bank is $xx.xx.
Where xx.xx is the actual total calculated. Do not worry about formatting to two decimal places, just output the answer. You may want to add some test values to the vector, but I am more concerned with the code
Explanation / Answer
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<double> dollars; // declare vector
bool more = true;
while (more) //enter double type values in it using push_bac
{
double d;
cout << " Please enter dollars, 0 to quit: ";
cin >> d;
if (d == 0)
more = false;
else
dollars.push_back(d);
}
double sum = 0;
int i;
for (i = 0; i < dollars.size(); i++) // sum of all elements of vector
sum = sum + dollars[i];
cout << " Sum = $"<<sum << " ";
return 0;
}
Output:
Please enter dollars, 0 to quit: 100.34
Please enter dollars, 0 to quit: 200.56
Please enter dollars, 0 to quit: 300.67
Please enter dollars, 0 to quit: 400.85
Please enter dollars, 0 to quit: 500.56
Please enter dollars, 0 to quit: 0
Sum = $1502.98
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.