C++ calculations not printing in proper format - c++

I am working on a homework assignment and when I run my program my calculations are being displayed as -7.40477e+61. I am using visual studio as my IDE and when I check my code on an online checker it displays just fine. I am not sure why everything is being printed in that format. Any advice would be great!
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
using namespace std;
int main()
{
double dArr[5];
long lArr[7] = { 100000, 134567, 123456, 9, -234567, -1, 123489 };
int iArr[3][5];
char sName[30] = "fjksdfjls fjklsfjs";
short cnt1, cnt2;
long double total = 0;
double average;
long highest;
srand((unsigned int)time(NULL));
for (int val : dArr) {
dArr[val] = rand() % 100000 + 1;
cout << dArr[val] << endl;
}
for (int count = 0; count < 5; count++) {
total += dArr[count];
average = total / 5;
}
cout << endl;
cout << "The total of the dArr array is " << total << endl;
cout << endl;
cout << "The average of the dArr array is " << average << endl;
cout << endl;
system("pause");
return 0;
}

The range-based for loop:
for (int val : dArr)
iterates val over the values of the collection dArr, not the indexes of that collection. So, when you attempt:
dArr[val] = rand() % 100000 + 1;
within said loop, it's unlikely to to give you the results you expect. Since dArr is local to main, it may have any values in it.
A better way would be to mirror your second loop, with something like:
for (int count = 0; count < 5; count++) {
dArr[val] = rand() % 100000 + 1;
cout << dArr[val] << endl;
}
Having said that, there appears to be no real reason why you're storing these numbers in an array at all (unless there's something about that in the problem statement that isn't shared in this question).
All you really need to do is keep the total, and the count so you can work out the mean. That could be as simple as (I've also changed the code to use Herb Sutter's AAA style, "almost always auto"):
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
const auto count = 5U;
srand((unsigned int)time(NULL));
auto total = 0.0L;
for (auto index = 0U; index < count; ++index) {
const auto value = rand() % 100000 + 1;
cout << value << "\n";
total += value;
}
const auto average = total / count;
cout << "\nThe total of the dArr array is " << total << "\n";
cout << "The average of the dArr array is " << average << "\n\n";
return 0;
}

Related

Not getting correct expected output on diceroll

I am currently working on this program to roll 2 dice. My program works however, for some reason my expected output is coming out as 0.000% for all roll sums instead of what it should be. I am sure I am overlooking something but I have no idea what. Any help is much appreciated!
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
const int ROLLS = 36000;
const int SIZE = 13;
const int CW = 10;
// array 'expected' contains counts for the expected number of times
// each sum occurs in 36 rolls
int expected[SIZE]= {0,0,1/36,1/18,1/12,1/9,5/36,1/6,5/36,1/9,1/12,1/18,1/36};
int sum [SIZE] = {0};
int die1;
int die2;
srand(static_cast<unsigned>(time(nullptr)));
for (int i = 0; i <=ROLLS; ++i) {
die1 = 1 + rand() % 6;
die2 = 1 + rand() % 6;
sum[die1+die2]++;
}
cout << fixed << showpoint << setprecision(3);
cout << setw(CW) << "Sum" << setw(CW) << "Total"
<< setw(CW) << "Expected" << setw(CW) << "Actual" << endl;
for (int j = 2; j < SIZE; ++j) {
cout << setw(CW) << j << setw(CW) << sum[j]
<< setw(CW-1) << (100.0 * expected[j] / 36) << '%'
<< setw(CW-1) << (100.0 * sum[j] / ROLLS) << '%' << endl;
}
return 0;
}
The type of expected is int, which means it's an integer. The results of all of your divisions are truncated to the lowest integer, which is always 0.
You need to:
Declare expected as a real number type, such as float or double
Use the correct literals to make the division produce real numbers, e.g. 5.0f/36 or 5.0/36.

multiplication of random numbers different from zero

I have a code that generates 10 random numbers and I need to calculate the sum and product of the non-zero numbers and display which numbers have been multiplied. I already have most of the code but I have no idea how to multiply numbers that are nonzero and then display them. Can someone help me?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int main()
{
cout << "draws 10 numbers:" << endl;
Sleep(1000);
cout << endl;
srand(time(0));
int sum=0;
int product=1;
for(int i=0, value=0; i<10; i++, sum+=value, product*=value)
{
value = rand()%10+0;
Sleep(1000);
cout << value << endl;
}
Sleep(1000);
cout << "the sum is " << sum <<endl;
cout << "the product is " << product <<endl;
return 0;
}
To start, it is easier to read and understand if we move the addition and multiplication out of the for loop header.
int sum = 0;
int value = 1;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
product *= value;
std::cout << value << std::::endl;
}
Next, we only want to do the multiplication if the value is not equal 0.
int sum = 0;
int value = 1;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
if(value != 0)
{
product *= value;
}
std::cout << value << std::::endl;
}
So the whole program looks like this.
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::cout << "draws 10 numbers:" << std::endl;
srand(time(0));
int sum = 0;
int product = 1;
int multiplied = 0;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
if(value != 0)
{
product *= value;
multiplied += 1;
}
std::cout << value << " ";
}
std::cout << std::endl;
std::cout << "the sum is " << sum << std::endl;
std::cout << "the product is " << product << std::endl;
std::cout << "numbers multiplied is " << multiplied << std::endl;
return EXIT_SUCCESS;
}

Finding min and max value in a random array

Working on an assignment that requires me to put in some functions (finding max/min value, sum and average value of random numbers in an array), I've managed to complete all of them but for min value I'm getting a value of -2145379808. I'm not sure where I've messed up and I would appreciate the help.
Code so far:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char** argv) {
{
cout << "Enter array size " << endl;
}
float avg;
float sum;
int size;
cin >> size;
int array[size];
int max = array [0];
int min = array [0];
srand((unsigned)time(NULL));
for (int i = 1; i < size + 1; i++)
{
array[i] = 1+rand()%100 ;
sum += array[i];
cout << "number " << i << " = "<< array[i] << endl;
}
for (int x = 1; x < size; x++){
if (array[x] > max){
max = array[x];
}
if (array[x] < min){
min = array[x];
}
}
cout << "\nmax = " << max << endl;
cout << "\nmin = " << min << endl;
cout << "\nsum = "<< sum << endl;
cout << "\navg = " << sum / size << endl;
return 0;
}
Setting max and min to the uninitialised element of array is never going to end well. On this note, you also need to initialise sum. You may as well remove avg since you don't use it.
You need to set max and min to the first element of array once you know what it is. Crudely, you could set max to std::numeric_limits<int>::min() and min to std::numeric_limits<int>::max().
Note also that the bounds of array are array[0] to array[size - 1]. Therefore you need to revisit the indexing in your loops.
Then once you have it working, bin it, and use std::vector<int>, and things like minmax_element: http://en.cppreference.com/w/cpp/algorithm/minmax_element
The problem is in following lines:
float avg;
float sum;
...
int max = array [0];
int min = array [0];
Because at this point the value at array [0] are garbage value.
To correct your code change this line as following (also include climits header file). Also, change loops index accordingly:
float avg = 0;
float sum = 0;
...
int max = INT_MIN;
int min = INT_MAX;
Following is corrected code(some changes made for optimization). See it working here:
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <climits>
using namespace std;
int main(int argc, char** argv) {
{
cout << "Enter array size " << endl;
}
float sum = 0;
int size;
cin >> size;
int array[size];
int max = INT_MIN;
int min = INT_MAX;
srand((unsigned)time(NULL));
for (int i = 0; i < size; i++)
{
array[i] = 1+rand()%100 ;
sum += array[i];
cout << "number " << i << " = "<< array[i] << endl;
if (array[i] > max){
max = array[i];
}
if (array[i] < min){
min = array[i];
}
}
cout << "\nmax = " << max << endl;
cout << "\nmin = " << min << endl;
cout << "\nsum = "<< sum << endl;
cout << "\navg = " << sum / size << endl;
return 0;
}
To insure your max and min are initialized correctly, C++ provides std::numeric_limits for all types. They each have max() and min() member functions to return the max and min value for the type. In any code you want to find a maximum and minimum, you want to first initialize your maximum to the minimum of the type and vice versa. That way any value will be larger than your min and smaller than your max.
You do that with std::numeric_limits similar to:
int min = std::numeric_limits<int>::max()
int max = std::numeric_limits<int>::min()
Let me know if you have more questions.

calculate average of array elements and display them

The problem is:
A Class of 40 students has received their grades for 5 exams. Implement a function that calculates the worst average grade and display the the IDs of all students having the worst average grade.‎
I already calculated the average but do not know how to calculate the WORST average ( as in the lowest average of the 40 students) and displaying the ID numbers that have this number.
This is what I have written so far:
#include<iostream>
#include <iomanip>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
int main()
{
float avg;
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
cout << "Enter an ID number: " << endl;
cin >> x[i];
cout << "Enter 5 grades: " << endl;
for (int j = 0; j < 5; j++)
{
cin >> y[j];
while (y[j]>100)
{
cout << "Please enter a valid grade that is less than a 100: " << endl;
cin >> y[j];
}
total += y[j];
}
avg = total / 5;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg << endl;
}
Something like this:
Note: I have added some important statements!
#include<iostream>
#include <iomanip>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
float AVG[MAX_NUM];
int worstIDCount = 0;
int main()
{
float avg, min = 1001;
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
avg = 0;
total = 0;
cout << "Enter an ID number: " << endl;
cin >> x[i];
cout << "Enter 5 grades: " << endl;
for (int j = 0; j < 5; j++)
{
cin >> y[j];
while (y[j]>100)
{
cout << "Please enter a valid grade that is less than a 100: " << endl;
cin >> y[j];
}
total += y[j];
}
avg = total / 5;
AVG[i] = avg;
if(avg < min)
min = avg;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg << endl;
}
for(int i = 0; i < MAX_NUM; i++)
{
if(AVG[i] == min)
cout << "Student with WORST Average: ID" << x[i] << endl;
}
};
So you want to store these averages in a std::vector<float>, std::sort it and get the lowest. Then go back and find the students that have that average.
working example
#include <iostream>
#include <vector>
#include <functional> // mem_fn
#include <algorithm> // sort, upper_bound
#include <iterator> // ostream_iterator
struct Student_average {
int student_id;
float average;
};
bool compare_student_averages(Student_average const &lhs,
Student_average const &rhs) {
return lhs.average < rhs.average;
}
int main() {
std::vector<Student_average> averages;
// collect the data and populate the averages vector
// ...
sort(begin(averages), end(averages), compare_student_averages);
std::cout << "The worst average is: " << averages.front().average << '\n';
auto end_of_worst_student_averages =
upper_bound(begin(averages), end(averages), averages.front(),
compare_student_averages);
std::cout << "The IDs of the students with the worst averages are:\n";
transform(begin(averages), end_of_worst_student_averages,
std::ostream_iterator<int>(std::cout, "\n"),
std::mem_fn(&Student_average::student_id));
}
Here is a more C++ way of doing this using std::accumulate and std::min_element (I removed the check for anything > 100, for brevity):
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
int main()
{
float avg[5];
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
cin >> x[i]; // ID
for (int j = 0; j < 5; ++j)
cin >> y[j]; // grades
// compute the average for this student
avg[i] = std::accumulate(y, y + 5, 0) / 5.0F;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg[i] << endl;
}
// compute the worst average
float* worst_average = std::min_element(avg, avg + MAX_NUM);
// get the position in the array where the worst is found
int position = std::distance(avg, worst_average);
// output results
cout << "This person has the worst average: " << x[position]
<<". The average is " << *worst_average << "\n";
}
Note that the averages are stored in an array. The way the average is computed for each person is to use std::accumulate to add up the y array values, and then divide by 5.0.
Since we now have the averages in an aray, we want to find the smallest item in the array. To do that, min_element is used to get us the position of where the element is stored.
The trick here is that min_element returns a pointer to the smallest item, so we need calculate how far this pointer is located from the beginning of the avg array. To do this, the std::distance function is used. This now gives us the position of the smallest item.
The rest of the code just outputs the results.
As you can see, the only loops involved were the input loops. The calculation of the average and the worst average were done using accumulate and min_element, respectively.

C++ Random & Array

I try to use the random function for different things.
For now it works but I get one problem is I want to generate randomly the F in my code but they need to become array after. Also I need to use it and if I need to do it 1 by 1 I think my code will be too long and messy.
Do you know how I can do this?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
srand(time(0));
//random numbers 1 to 10 for Time:
int t = rand() % 10 + 1 ;
cout << "There is "<< t << " Time;
int* F1 = new int [t];
int* F2 = new int [t];
int* F3 = new int [t];
int* F4 = new int [t];
int* F5 = new int [t];
cout << "Time per F: 0 Not available, 1 available;
//For F1
for(int i = 0; i < t; i++){
//random numbers 0 or 1:
F1[i] = rand() % 2 ;
}
cout << "The Time for F1 is ";
for(int a = 0; a < t; a++){
cout << " "<< F1[a] <<" ";
}
//For F2
for(int j = 0; j < t; j++){
//random numbers 0 or 1:
F2[j] = rand() % 2 ;
}
cout << "The Time slot for F2 is ";
for(int b = 0; b < t; b++){
cout << " "<< F2[b] << " ";
}
return 0;
}
Thank you
Edit: With the solution you give me helps to find the solution
I do int F[em][t];
Since you are using C++, and have access to the standard library, this could be written much cleaner as safer as a std::vector:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
srand(time(0));
//Random number from 3 to 7
int numberOfVectors = (rand() % 7) + 3;
//Random number from 1 to 10.
int size = (rand() % 10) + 1;
std::cout << "There are " << numberOfVectors << " vectors." << std::endl;
std::cout << "Each vector has " << size << " elements." << std::endl;
std::vector< std::vector<int> > vectorOfVectorOfInt;
std::cout << "Value per element: 0 = Not available, 1 = available" << std::endl;
for(int vec = 0; vec < numberOfVectors; vec++)
{
//Create a new vector with 'size' elements.
std::vector<int> newVector(size);
for(int i = 0; i < size; i++)
{
//Generate a random value between 0 and 50
newVector[i] = (rand() % 50);
}
//Add the vector to our vector-of-vectors.
vectorOfVectorOfInt.push_back(newVector);
std::cout << "The values for Vector #" << (vec+1) << " is:";
for(int b = 0; b < size; b++)
{
int value = vectorOfVectorOfInt[vec][b];
std::cout << "\t" << value;
}
std::cout << std::endl;
}
return 0;
}
You can run it and see the results here: http://ideone.com/RWQhjO
Use an array of array:
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
srand(time(0));
//random numbers 1 to 10 for Time:
int t = rand() % 10 + 1 ;
cout << "Time per F: 0 Not available, 1 available";
const int f_num = 5;
cout << "There is "<< t << "Time";
int* F = new int*[f_num];
for(int i = 0; i < f_num; i++){
F[i] = new int[t];
cout << "The Time for F"<<i<<" is :";
for(int j = 0; j < t; j++){
//random numbers 0 or 1:
F[i][j] = rand() % 2 ;
cout << " "<< F1[i][j] <<" ";
}
}
}
BTW, your code is C-like. In C++, we usually use std::vector instead of plain array, and http://en.cppreference.com/w/cpp/numeric/random instead of rand() . Also, don't use using namespace std . This can cause name clashes.
I try to use the random function for different things.
Random things, presumably.
For now it works but I get one problem is I want to generate randomly the F in my code but they need to become array after.
You can generate this just as you generated your value for t.
const int number_of_fs = rand() % 10 + 1;
std::cout << "Working with " << number_of_fs << " Fs" << std::endl;
Also I need to use it and if I need to do it 1 by 1 I think my code will be too long and messy. Do you know how I can do this?
Your code is already too long and messy and has memory leaks. You should be using containers from the Standard Containers library, rather than pointers to pointers that never get deleted.
Here is how your code might look were you to use a std::map of std::vectors for instance:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iterator>
#include <map>
#include <vector>
int main(){
srand(time(0));
//random numbers 1 to 10 for Time:
const int t = rand() % 10 + 1;
std::cout << "There is "<< t << " Time" << std::endl;
const int number_of_fs = rand() % 10 + 1;
std::cout << "Working with " << number_of_fs << " Fs" << std::endl;
std::map<int, std::vector<int> > f;
std::cout << "Time per F: 0 Not available, 1 available" << std::endl;
for (int f_slot = 1; f_slot <= number_of_fs; ++f_slot) {
for(int i = 0; i < t; i++){
//random numbers 0 or 1:
f[f_slot].push_back(rand() % 2);
}
std::cout << "The Time for F" << f_slot << " is " << std::endl;
std::copy(f[f_slot].begin(), f[f_slot].end(),
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
}
See it run!
Population and printing of the contents of these containers should probably be extracted into separate functions, of course, but I didn't want to re-write your code completely.