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.
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.
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;
}
Related
Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific.
I am writing a code that takes a user input between 0 and 511 and converts it into a binary number. Then the program will replace all the 1's in the binary number with T and all the 0's in the number as H. Afterwards it will print out the results (the binary number with the H and T replacement) as a 3*3 matrix.
This is the desired output (not what I have but what I want):
Enter a number between 0 and 511: 299
The binary number is: 100101011
The matrix is:
THH
THT
HTT
The problem with my code is that I am unsure of how to replace an array that consists of all integers to have certain parts of the index to be either characters or strings. For sure the part with the binary number conversion works but the replacement of the 0's and 1's of the array is where the trouble is at. I am also unsure of how to print out the matrix result. I assume it goes either of 2 ways: 1. The program creates a new array for the previous array's elements stored and prints out the matrix array instead. 2. There is a way to only print the array 3 lines at a time. The only way I can think of is to somehow cut the for loop short and add a line break after every 3 values. I am aware that there are a few pointable errors in my code but I do not know how to fix them.
Although this is in the C++ language, what I have learned is the C style syntax (no std:: kinds of code or stuff like that because I haven't learned it yet and I will not understand it) So far I have learned basic arrays, loops, and functions.
#include <iostream>
using namespace std;
int main(){
int arr[10];
int input, i;
cout<<"Enter a number between 0 and 511: ";
cin>> input;
for(i = 0; input > 0; i++){
arr[i] = (input % 2);
input = input / 2;
}
cout<<"The binary number is: ";
for(i = i - 1; i >= 0; i--){
cout<<arr[i];
}
string newArr[10] = arr[10]; //the error here states that the array initializer must be an initializer list
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
if(arr[i] == 1){
arr[i] = "T"; //the error here mentions that a string/ character cannot be assigned with a integer array
}
else{
arr[i] = "H";
}
}
for(int i = 0; i < sizeof(arr)/sizeof(arr[10]); i++){
cout<<arr[i]<< " ";
}
}
This would be sufficient:
#include <iostream>
using namespace std;
int main()
{
// you never actually checked if the input is valid
// so you may or may not want this loop:
int input;
do
{
cout << "Enter a number between 0 and 511: ";
cin >> input;
} while ((input < 0) || (input > 511));
// space for matrix, new lines and null
// to construct a null terminated string
char buffer[3 * (3 + 1) + 1];
int i = 0;
// since the bits are read from left to right
// I will use a mask instead of bit shifting the input
int bit = 1 << 9;// 2^9 == 512
for (int r = 0; r < 3; r++)// rows
{
for (int c = 0; c < 3; c++)// columns
{
// this could come after the check
// and then bit would start at 256
bit >>= 1;
// perform the check and add the corresponding letter
buffer[i++] = (bit & input) ? 'T' : 'H';
}
// add new lines
buffer[i++] = '\n';
}
// if you don't want the last '\n'
// this could be { buffer[--i] = '\0'; }
buffer[i++] = '\0';
cout << buffer;
}
The listed code is from a larger project that I am working on (I deleted almost everything else that wasn't necessary for this posting) that is having some trouble running properly. I found the line that is causing the error but I'm hoping for an explanation as to why this line is causing it.
#include <iostream>
#include <tgmath.h>
using namespace std;
int main() {
const int m = 2; // Number of rows
const int n = 2; // Number of cols
int totalPoss = 0; // Number of unique possibile m X n binary matrices
// 2^(m * n) = the number of unique binary
// combinations of m X n matrices
int stop = pow(2, m * n);
// Error when a = 0, 1 | m = 0 | n = 1
for (int a = 0; a < stop; a++) {
int poss[m][n] = {0}; // 2D Array to store each possible matrix
int nextGen[m][n] = {0}; // 2D Array to store the next generation of cells
int rem[m * n]; // 1D Array to store the binary entries of the poss[m][n]
totalPoss = a;
int hold = a; // Stores the current "possibility number" (i.e when
// a = hold = 1 the binary equivilent of 1 will be stored
// in rem[m * n])
// Generate binary number based on whatever a is at current iteration
int c = 0;
while (hold > 0) {
// storing remainder in binary array
rem[c] = hold % 2;
hold = hold / 2;
c++;
}
cout << "Binary: ";
for (int i = 0; i < (m * n); i++) {
cout << rem[i] << " ";
}
cout << endl << endl;
}
cout << "Total possibilities: " << totalPoss+1 << endl;
return 0;
}
The line in question is line 19, or int nextGen[m][n] = {0};. The program's purpose in this state is to output all possible unique binary numbers of 4 bits. The number to translate to binary is determined by the initial for loop. The number is translated in the while loop and stored in rem[m][n]. This code works fine unless you include line 19. For whatever reason when this 2D array is created the output for 0 and 1 is 1 14 0 0 but outputs correctly for 2-15. My question is why this one (seemingly) unrelated line breaks my code.
Thank you!
rem is not completely initialized. The loop that assigns values only iterates until hold is zero, so it does not set the higher elements. But the loop that prints it always prints n * m elements.
The effect of defining nextGen is incidental. It may affect where rem is placed in memory, resulting in it happening to contain zeroes rather than other bits (and likely you are compiling without optimization).
Initialize rem to all zeroes or change the loop that sets its elements.
I'm trying to find all the prime numbers between two integers and place them in an integer array.
The catch is that i have to use a specific method of doing so (divide each subsequent integer by all the primes in my array). So I can't use the sieve of Eratosthanes or any other 'easier' methods.
My code successfully prompts the user for two integers, but for now I do not use either of them. First I want to make sure the program works for values between 0 and whatever, in this case 200 just to test it.
Problem is, when I run the program and print the first 20 or so values in the array, I'm getting
2, 3, 5, 7, 11, 200, 0, 0, 0, 0, 0, 0 ...... more zeroes.
The first 5 values are correct because they start in the array, but after that the whole thing goes haywire.
I've worked through my nested loop by hand for a couple values and it SEEMS like it should work. I feel like there's a specific array property that I'm overlooking.
Here's my code:
#include "stdafx.h"
#include "iostream"
#include "climits"
#include "cmath"
#include "array"
using namespace std;
int main()
{
// declare variables to store user input
int lowerBound, upperBound;
// prompt user for lesser and greater integers and store them
cout << "Program to find all primes between two integers." << endl;
cout << "Enter lesser integer: " << endl;
cin >> lowerBound;
cout << "Enter greater integer: " << endl;
cin >> upperBound;
// if statement to switch the input variables if the user accidentally enters them backwards
if (lowerBound > upperBound) {
int temp = lowerBound;
lowerBound = upperBound;
upperBound = temp;
}
// initialize int array with the first 5 primes
int primes[100] = { 2, 3, 5, 7, 11 };
// loop to find primes between 12 and 200 (since we already have primes from 1-11 in the array)
for (int i = 12; i <= 200; i++) {
// the maximum divisor needed to determine if the current integer being tested is prime
double maxDivisor = sqrt(i);
// variable for the current size of the array
int size = 5;
// boolean variable is set to true by default
bool isPrime = true;
for (int j = 0; j < size; j++) { // changed "j<=size" to "j<size"
int remainder = (i % primes[j]);
// once the maximum divisor is reached, there is no need to continue testing for the current integer
if (primes[j] > maxDivisor) {
break;
}
// if the remainder of divison by a prime is 0, the number is not prime, so set the boolean variable to false
if (remainder = 0) {
isPrime = false;
}
}
// if isPrime is still true after the nested loop, the integer value being tested will be placed in the next element of the array
if (isPrime == true) {
primes[size] = i;
// since we added to the array, increment size by 1
size++;
}
}
// display the first 20 values in the array for debugging
for (int k = 0; k < 20; k++) {
cout << primes[k] << ", ";
}
system("pause");
return 0;
}
This here
if (remainder = 0) {
isPrime = false;
}
Needs to be changed to
if (remainder == 0) {
isPrime = false;
}
Because = does assignment, not comparison. So what remainder = 0 does it setting remainder to 0, and then it returns that 0, which gets casted to false, which is on of the reasons why it's not finding any primes.
Also, as Fantastic Mr Fox pointed out, for (int j = 0; j <= size; j++) needs to be changed to for (int j = 0; j < size; j++).
Also, did your compiler issue any warnings? If not, try to see if you can set it to be more strict with warnings. I figure most modern compilers will give you a hint at if (remainder = 0). Getting useful warnings from the compiler helps a lot with preventing bugs.
Edit:
As Karsten Koop pointed out, you need to move the int size = 5; out of the loop, to before the for (int i = 12;. With those changes, it's now working on my machine.
Last but not least, a tip: instead of if (isPrime == true), you can just write if (isPrime).
So, i've made a program which is able to sort arrays, and i'm trying to sort an array containing double FP's, including 2-3 random ones i enter, pos inf, neg inf and a single NaN. so for this purpose i wish to sort the NaN.
So my code works, however when trying to sort the NaN, i'm unable to do so. What i'd like to do is sort it to the end, or have it put at the end of the sorted array. Is there anyway I can actually do this? Thanks in advance!!! code is as follows:
int main()
{
int start_s = clock();
int n, k = 4, j; // k is number of elements
double x = -0.0;
double i = 0;
double swap = 0;//used in the function as a place holder and used for swapping between other variables
double a[100] = { (1/x) + (1/i), 2.3, 1/x *0, 1/i };//array of double elements // 1/i * 0 is NaN
//(1 / i) * 0
for (n = 0; n < (k - 1); n++) // for loop consists of variables and statements in order to arrange contents of array
{
for (j = 0; j < k - n - 1; j++)
{
if (a[j] > a[j + 1])
{
swap = a[j];
a[j] = a[j + 1];
a[j + 1] = swap;
}
}
}
cout << "The list of sorted elements within the array, is: " << endl; /* Output message to user */
for (int i = 0; i < k; i++)// Loop up to number of elements within the array
{
cout << a[i] << " ";/* Output contents of array */
}
cout << endl; //new line
int stop_s = clock();
cout << "The execution time of this sort, is equal to: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000 << " milliseconds" << endl;
return 0;
Since you're in C++ land anyway, why not use it to the full. First, indeed, move the NaN's and then sort. I've taken out 'noise' from your code and produced this, it compiles and runs (edit: on gcc-4.4.3). The main difference is that the NaN's are at the beginning but they're easily skipped since you will get a pointer to the start of non-NaN's.
#include <iostream>
#include <algorithm>
#include <math.h>
int main()
{
int n, k = 4, j; // k is number of elements
double x = -0.0;
double i = 0;
double a[100] = { (1/x) + (1/i), 2.3, 1/x *0, 1/i };//array of double elements // 1/i * 0 is NaN]
double *ptr; // will point at first non-NaN double
// divide the list into two parts: NaN's and non-NaN's
ptr = std::partition(a, a+k, isnan);
// and sort 'm
// EDIT: of course, start sorting _after_ the NaNs ...
std::sort(ptr, a+k);
cout << "The list of sorted elements within the array, is: " << endl; /* Output message to user */
for (int i = 0; i < k; i++)// Loop up to number of elements within the array
{
cout << a[i] << " ";/* Output contents of array */
}
cout << endl; //new line
return 0;
}
Do a linear scan, find the NaNs, and move them to the end - by swapping.
Then sort the rest.
You can also fix your comparator, and check for NaN there.
For the actual check see: Checking if a double (or float) is NaN in C++
you can use isnan() in cmath to check for NaNs. So, you can just change your comparison line from:
if (a[j] > a[j + 1])
to:
if (!std::isnan(a[j + 1]) && std::isnan(a[j]) || (a[j] > a[j + 1]))
just a reminder, you need to have:
#include <cmath>
at the top of your code.
I am working on a homework assignment where I calculate the values in an interval of integers of a function (f(x) = x * x – 12 * x + 40) in a 'for' loop. I need to find a minimum value. That's all fine, but I also need to keep the index number for which the value was smallest. At the moment I reiterate the function again in another loop, but this looks really messy. Also I could derive x and calculate the answer using the known minimum, but that's also weird, because derivation is not so straightforward. Do you have any tips for me? Thanks.
#include <iostream>
#include "limits.h"
using namespace std;
int main ()
{
int lBound, uBound, y, min;
cout << "Give the lower and the upper bounds of integer numbers: " << endl;
cin >> lBound >> uBound;
min=INT_MAX;
int x = lBound;
for (int i = x; i <=uBound; i ++) {
y = i * i - 12 * i + 40;
cout << x << " " << y << endl;
if (y<min) {
min=y;
}
x++;
}
for (int i = lBound; i <= uBound; i++) {
y = lBound * lBound - 12 * lBound + 40;
if (y==min) {
y = lBound;
i=uBound; // terminates the loop
}
lBound++;
}
cout << "smallest value of the function is " << min << " for x = " << y << endl;
return 0;
}
Here's a hint: Whenever you need to "keep something around" in a program, that means you need to store it in a variable. Whether that variable is local, global, or passed around depends on how long you need to keep it around. This is called the variable's "scope". It's considered good practice to keep the scope of any variable to a minimum, hence the guidelines discouraging globals.
i=uBound; // terminates the loop
This is not a very good coding practice. To terminate a loop, you should use a flow control construct like break. Doing so in this case would preserve the index of the minimum element.
Edit: If you want i to outlive the loop, you simply need to declare it outside. To wit:
change
for (int i = lBound; i <= uBound; i++) {
to
int i; // variable exists outside loop
for (i = lBound; i <= uBound; i++) {
Furthermore, just FYI, loop bounds are usually specified as half-open intervals to avoid the potential issue where lbound and ubound represent the limits of the int data type. This means that you usually use < instead of <=.
It's not clear if you're in an algebra class or a CS class…