I am just learning C++ and I want to add this piece of code to a project. I have created a vector from values entered by a user. I want to then subtract each value from each other from the beginning to the end. For example if a user enters 10,4,3 the program will subtract the values in that order 10 - 4 - 3 and output 3 as the solution. I figured how to do it with addition but can't get it to output for subtraction.
#include <iostream>
#include <vector>
usingnamespace std;
//Subtraction using vectors
int main()
{
vector<double>vectorValues;
int Size, subtraction, temp;
double values;
cout << "How many values you want to subtract: ";
cin >> Size;
int i = Size;
for(i = 0; i < Size; ++i)
{
cout << "Enter the values to be subtracted: ";
cin >> values;
vectorValues.push_back(values);
}
cout << "You want to subtract a total of "<< int(vectorValues.size()) << " numbers. \n";
for(int i = 0; i < vectorValues.size(); i++)
{
//subtraction -= vectorValues[i]; <--This is where I'm stuck
cout << vectorValues[i] << ", ";
}
cout << "The subtraction of these values is: " << subtraction << "\n\n";
system("pause");
return 0;
}
Set your subtraction value equal to vectorValues[0] before the subtraction for loop so it knows where to start. Then your for loop is basically correct (you will want to skip vectorValues[0] in the loop through either by starting at 1 or using an if statement).
Okay I think I'm almost there my problem now is its subtracting from the first entered number only. So when I put in a vector of three numbers 10, 3, 2 it give me the answer 7 and 8 instead of 5. Kind of the same problem I was having earlier before the changes. How can I get it to subtract value to next value.
You need to set subtraction = vectorValues[0]; before the for loop, otherwise it is just going to go back to that number every time and subtraction -= vectorValues[i]; wont do anything.
1 2 3 4 5 6 7 8
subtraction = vectorValues[0]; // Number to start from (eg. 10)
for(int i = 1; i < vectorValues.size(); i++)
{
subtraction -= vectorValues[i]; //Loop through and subtract each number
cout << vectorValues[i] << ", ";
cout << "The subtraction of this value: " << subtraction << "\n\n";
}
Man thanks so much straight forward answer to my problem unlike some other people on those other boards that just beat about the bush but don't provide any type of guide, hints, or solution. Much appreciated.