I have two problems that I am stuck on. First the total accumulator is all over the place. one time I run the program and get a correct answer and the next it is way off. Second how do I print the string that is parallel to the number that I get when I run the highest and lowest? And what am I doing wrong? Every time I run this I get the last element of each array. Here is what I have so far.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
constint size = 5;
string salsa[size] = {"Mild", "Medium", "Sweet", "Hot", "Zesty"};
int sold[size];
int total;
string lowType, highType;
int lowest, highest;
cout<<"Enter the total number of jars sold for each type of salsa:\n";
for (int count=0; count<size; count++)
{
cout<<"For "<<(salsa[count])<<endl;
cin>>(sold[count]);
while(sold[count]<0)
{
cout<<"Sales cannot be less than 0.\n";
cin>>(sold[count]);
}
total+=(sold[count]);
}
for (int count=0; count<size; count++)
{
cout<<(salsa[count])<<" sold "<<(sold[count])<<" units last month.\n";
}
lowType=salsa[0];
lowest=sold[0];
for (int count=1; count<size; count++)
{
if (sold[count]<lowest)
lowest=sold[count];
lowType=salsa[count];
}
highType=salsa[0];
highest=sold[0];
for (int count=1; count<size; count++)
{
if (sold[count]>highest)
highest=sold[count];
highType=salsa[count];
}
cout<<"The total number of jars sold was "<<total<<endl;
cout<<"The salsa with the lowest sales is "<<lowType<<endl;
cout<<"The salsa with the highest sales is "<<highType<<endl;
system("pause");
return 0;
}
You forgot {}s around lines 36, 37 and 44, 45. By the way, ()s when dealing with cin and cout are not needed as []s have higher precedence than >> and <<. If you're ever in doubt, find yourself an operator precedence table, to avoid silly ()s.
As for total, it is never set to 0, so could hold any garbage value.
Facepalm... Something that simple. The high/low is now working perfect, but the total still jumps around. I just put 5,4,3,2,1 in and got 105 as an answer. Then ran it again with the same numbers and got 15. Any thoughts on what is causing this to happen?
You probably just made a typo somewhere when you were testing with that input.
(You probably actually entered something like 55, 44, 3, 2, 1, which gives a total of 105)
Or at least I'm consistently getting 15 for the total with 5,4,3,2,1 as input.
I wish it was that simple. I know I am not doing any typos. I have tried several other numbers as well and the same problem happens. If you are getting consistent answers then maybe there is a problem with Visual Studios Express that I am using.