When the is 200 the program doesn't read it. How to solve this problem? The program needs to print the ranges and the numbers but if the user input 200 it doesn't work. For example the user input numbers 180, 190, 200. The expected out put is 3 but the output is only 2. See the image attached for more details.
CodePudding user response:
Note that in the statement:
results[scores[i] / 25] ;
You should check that the expression scores[i] / 25
is within the size of the vector results
otherwise this is undefined behavior.
In your case, for the value 200
the expression scores[i] / 25
comes out to be 8. But since the size of the results
vector is 7
, your going out of bounds and this leads to undefined behavior.
You can use std::vector.at()
member function to prevent this from happening. So you can modify that statement to look like:
results.at(scores[i] / 25) ;//this will throw if you go out of bounds
This has the advantage that your program will now not have undefined behavior.
You can also add a check to see if scores[i] / 25
is greater than or equal to the size of the results
vector, then you can ask the user again for input.
CodePudding user response:
If you'd like to use fixed-sized vectors, make sure the largest input score isn't too large. In my example, you can take the min of the input value and the largest allowed number. If you have N=25 buckets, and the largest number you accept is 200, then 200/25=8 is the largest bucket index you would like to reach, meaning you need a bucket of size 9.
#include <iostream>
#include <vector>
using namespace std;
double largest_allowed_score = 200; // if a score is larger than this, use this value isntead of the score
size_t N = 25; // number of entries to read in, results has the size of largest_allowed_score/N 1
```cpp
#include <iostream>
#include <vector>
using namespace std;
double largest_allowed_score = 200; // if a score is larger than this, use this value isntead of the score
size_t N = 25; // number of entries to read in, results has the size of largest_allowed_score/N 1
int main()
{
vector<double> scores(N);
cout << "Enter Score: \n";
for (size_t i = 0; i < N; i)
{
double val;
cin >> val;
val = min(val, largest_allowed_score);
scores[i] = val;
}
size_t res_size = static_cast<int>(largest_allowed_score) / N 1; // the number of buckets, result size, or resolution
vector<double> results(res_size);
// count the occurances in each bucket
for (size_t i = 0; i < N; i )
results[static_cast<int>(scores[i]) / N] ;
// print the buckets
for (size_t i = 0; i < res_size; i )
cout << i * N << " - " << (i 1) * N << ": " << results[i] << endl;
return 0;
}