because i type inn 72 and it shows 2 (which is right) but then if i type inn 72, and it shows 4 this time (it keeps increasing by 2 each time. it does the same with any number i type inn. this is my code:
#include %26lt;iostream%26gt;
using std::cout;
using std::cin;
using std::endl;
int main()
{
//declare array
int count = 0;
int searchFor = 0;
int scores[20] = {90, 54, 23, 75, 67, 89, 99, 100, 34, 99,
97, 76, 73, 72, 56, 73, 72, 20, 86, 99};
while (searchFor != -1)
{
// User enters a score
cout %26lt;%26lt; "Enter a score from 0 to 100: " ;
cin %26gt;%26gt; searchFor;
// If score is in the array, then add to count
for (int x = 0; x %26lt; 20; x = x + 1)
{
if (scores[x] == searchFor)
count = count + 1;
//end if
//end for
}
// Display count
cout %26lt;%26lt; "Count: " %26lt;%26lt; count %26lt;%26lt;endl;
}
return 0;
}//end of the searchArray function
Help with C++ please!!!! this program should show how many students earned a specific score. it is not working
You need to reset count each time you start over.
do like so:
while (searchFor != -1)
{
// User enters a score
count = 0;
cout %26lt;%26lt; "Enter a score from 0 to 100: " ;
cin %26gt;%26gt; searchFor;
// If score is in the array, then add to count
for (int x = 0; x %26lt; 20; x = x + 1)
{
if (scores[x] == searchFor)
count = count + 1;
//end if
//end for
}
// Display count
cout %26lt;%26lt; "Count: " %26lt;%26lt; count %26lt;%26lt;endl;
}
return 0;
}
Reply:The problem is because of the scope of the count variable. it is initialized before while loop. So after the while loop ends once, the count variable doesn't de-initialize. Put the declaration of count within the while loop, that way each time the loop begins, the count is re-initialized.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment