How to deallocate memory - c++

I have a void function which I call in the main and I want it to use a new value for pi each time is called, and not adding them. I thing I should deallocate the memory for the array of type Dir, but I can't figure it out. The implementation is as follows:
void throwSeries(int n)
{
double pi;
double faults;
double numCicle;
Dir c[n];
int count = 0;
for (int i = 0; i < n; i++)
{
c[i] = someFun(); // Returns type Dir
if (below(c[i]))
{
numCicle++;
}
}
pi = 4 * (numCicle / (double) n);
faults = ((pi - M_PI) / M_PI) * 100;
cout << setw(15) << setfill(' ') << n;
cout << fixed << setprecision(5);
cout<< setw(15)<< setfill(' ') << pi << setw(15)<< setfill(' ') ;
cout << fixed << setprecision(1);
cout << faults << endl;
}
int main()
{
system("CLS");
srand(time(0));
cout << setw(15) << "n" << setw(15) << "pi" << setw(15) << "faults" << endl;
cout << setw(15) << setfill('-') << "|"<< setw(15) << setfill('-') << "|";
cout << "--------------" << endl;
int n = 0;
for (int i = 0; i < 100; i++)
{
n += 100;
throwSeries(n);
}
return 0;
}
A print out example is as follows:
n pi Rel. fault
--------------|--------------|--------------
100 3.12000 -0.7
200 4.66000 48.3
300 6.28000 99.9
400 7.80000 148.3
500 9.40000 199.2
600 10.76000 242.5
And the values of pi shouldn't be added in each iteration.

You have to initialize numCicle before adding something to that.
In other words,
double numCicle;
should be
double numCicle = 0;

Related

Not outputting the calculation, just 0

I have my code here and it runs, however, when I try to output the percentage it just outputs 0, I've spent a long time trying to figure out what I'm missing and I'm clueless. Basically I'm trying to output the percent of votes for each candidate out of total votes. Any help would be appreciated. Here is my output;
Output display Also, im aware that the winner loops through every user until it reaches the end for some reason, still trying to work out the kinks.
Here is my code -
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class candidatesElection
{
public:
string last;
float votePercent;
void winnerOfElection();
void outputDis();
int total = 0;
};
int main()
{
string lastName[5];
int amountOfVotes[5];
double percentTotal[5];
int total = 0;
int winnerNo = 0;
int winningCandidate;
string winningName;
for (int i = 0; i < 5; i++)
{
cout << "Enter the last name of the Candidate: " << endl;
cin >> lastName[i];
cout << endl;
cout << "Enter the votes received by the Candidate: " << endl;
cin >> amountOfVotes[i];
total += amountOfVotes[i];
cout << "Total number of votes is: " << total << endl;
}
for (int i = 0; i < 5; i++)
{
if (amountOfVotes[i] > amountOfVotes[winnerNo]) winnerNo = i;
amountOfVotes[i] = amountOfVotes[winnerNo];
}
for (int i = 0; i < 5; i++)
{
percentTotal[i] = (amountOfVotes[i] / total) * 100.0; // need to make it floating point
}
void outputDis();
{
cout << endl << left << setw(25) << "Candidate" << right << setw(25) << "Votes Received" << setw(25) << "% of Total Votes" << endl;
for (int i = 0; i < 5; i++)
cout << endl << left << setw(25) << lastName[i] << right << setw(25) << amountOfVotes[i] << setw(25) << percentTotal[i] << endl;
cout << endl << left << setw(25) << "Total" << right << setw(25) << total << endl;
for (int i = 1; i < 5; i++)
{
int winHigh = amountOfVotes[0];
string win = lastName[0];
if (amountOfVotes[i] > winHigh)
{
winHigh = amountOfVotes[i];
win = lastName[i];
}
cout << "The Winner of the Election is " << win << endl;
}
}
system("pause");
};
The coefficient amountOfVotes[i] / total in (amountOfVotes[i] / total) * 100.0 is evalated in integer arithmetic: i.e. any fraction is discarded.
So you end up with 0 * 100 for all cases where amountOfVotes[i] is less than total.
The solution is to rearrange the formula to 100 * amountOfVotes[i] / total;, or, even better 100.0 * amountOfVotes[i] / total; which will force evaluation in double precision floating point - you are in danger of overflowing an int which, on some systems, can have an upper limit as low as 32767.
That's not immediately obvious even when using a line-by-line debugger. But do use that debugger to work out the other "kinks".

Unhandled exception at 0x012B1CA9

I am new to C++ and am trying to build a simple program that with the users input to proceed will generate a random left or right. I had the program working correctly until I added in the array to try and store each item as I have to output them as soon and the user would like to exit the loop. The program seems to compile fine but at run time I receive "Unhandled exception at 0x012B1CA9" Any help would be greatly appreciated.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = '100';
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
for (int i = 1; i < MAX; i++)
{
srand(time(NULL));
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
You have a multi-character constant here... and the behavior doesn't go as expected...
Change this line
const int MAX = '100';
to
const int MAX = 100;
Note the removed single quotes.
And secondly, I will advice you to remove the Seed of the C random generator from the for loop because, you'll likely get the same values from the rand() if you always call it immediately after seeding...
But preferable use the algorithm from C++'s random header
Here is a corrected version of your original code....
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int userSelection = 1;
const int MAX = 100; // <---changed
int randNum(0);
int one (0);
int two (0);
int total(0);
int sel[MAX];
do
{
cout << "Press 1 to pick a side or 0 to quit: ";
cin >> userSelection;
srand(time(NULL)); //< moved to here
for (int i = 0; i < MAX; i++) // <-- modified starting index
{
sel[i] = 1 + (rand() % 2);
if (sel[i] == 1)
{
cout << "<<<--- Left" << endl;
one++;
total++;
}
else
{
cout << "Right --->>>" << endl;
two++;
total++;
}
}
} while (userSelection == 1);
cout << "Replaying Selections" << endl;
for (int j = 0; j < MAX; j++)
{
cout << sel[j] << endl;
}
cout << "Printing Statistics" << endl;
double total1 = ((one / total)*100);
double total2 = ((two / total)*100);
cout << "Left: " << one << "-" << "(" << total1 << "%)" << endl;
cout << "Right: " << two << "-" << "(" << total2 << "%)" << endl;
system("pause");
return 0;
};
I think that it is basically good idea to read more about C data types and declaration. Your error:
const int MAX = '100' should be const int MAX = 100 without any quotes. C++ does implicit conversion from character literals to int.

passing arrays to functions C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i need help creating 7 functions to break this code into. By using pass by reference. i can't figure out how to pass the multidimensional arrays between functions.
#include <fstream>
#include <string>
#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int courseSize = 3;
const int examSize = 6;
int n=0;
int strLength =0;
double scoreTotal =0;
char lettergrade;
string header, name, address, phone, social, course, studentID;
const int letterGrade_A = 90;
const int letterGrade_B = 80;
const int letterGrade_C = 70;
const int letterGrade_D = 60;
int age, yearsAtTXST, numstudents;
double testscore;
double numGrade = 0;
const int minStrLength = 1;
const int maxStrLength = 100;
const int minint = 1;
const int maxint = 100;
const int minCourse = 1;
const int maxCourse = 3;
const int minTest = 1;
const int maxTest = 5;
const double test1 = 0.10;
const double test2 = 0.15;
const double test3 =0.15;
const double test4 = 0.20;
const double final_test = 0.40;
const double maxGrade = 100.0, minGrade = 1.0;
//initialize arrays
string nonNumerical[studsize][strSize];
int numeric1[studsize][numSize];
double numeric2[studsize][courseSize][examSize];
char lettergrades[studsize][courseSize];
cout << fixed << showpoint << setprecision(2);
//opening files
ifstream inputFile;
inputFile.open("Project4_A04314548_Input.txt");
ofstream fout;
fout.open ("Project4_A04314548_Output.txt");
if( !( inputFile && fout))
{
cout << "Error opening file.\n";
}
cout << " Enter a number of students: ";
cin >> numstudents;
while( !(numstudents ==3))
{
cout << " error number of students must be 3. Enter again: ";
cin >> numstudents;
}
//take in string data from input file
for(int x =0; x< studsize; x++)
{
for(int y=0; y < strSize; y++)
{
if(y >= strSize)
break;
getline(inputFile, nonNumerical[x][y]);
strLength = nonNumerical[x][y].length();
if(strLength < minStrLength || strLength > maxStrLength)
{
fout << " The given string for nonNumerical [" << x << "][" << y <<
"] is not within the proper range of 1-100 characters." << endl;
fout << " Please fix the issue and rerun the program for a correct
output." << endl << endl;
continue;
}
}
}
//above put into input data function
//take in data from input file
for(int x=0; x<studsize;x++)
{
for(int y=0; y < numSize; y++)
{
if(y>=numSize)
break;
inputFile >> numeric1[x][y];
if( numeric1[x][y] < minint || numeric1[x][y] > maxint)
{
fout << "The given integer for numerical1[" << x << "][" << y <<
"]is not within the proper range of 1-100." << endl;
fout << " please fix the problem and rerun the program for a correct
output." << endl << endl;
break;
}
}
}
//above put into data function
// take in double data from input file
for( int x1=0; x1<studsize; x1++)
{
for(int x2=0; x2 < courseSize; x2++)
{
for(int x3=0; x3<(examSize-1);x3++)
{
if(x3 >=(examSize-1))
break;
inputFile >> numeric2[x1][x2][x3];
if( numeric2[x1][x2][x3] < minGrade || numeric2[x1][x2][x3] >
maxGrade)
{
cout << "The given value fro numeric2[" << x1 << "][" << x2
<< "][" << x3 << "] is not within the proper range of 1-100" << endl
<< "Please fix the issue and rerun the program for a correct
output." << endl;
break;
}
else if( x3 == 0)
scoreTotal += (numeric2[x1][x2][x3]* test1);
else if( x3== 1)
scoreTotal += (numeric2[x1][x2][x3]* test2);
else if( x3 == 2)
scoreTotal += (numeric2[x1][x2][x3]* test3);
else if( x3 == 3)
scoreTotal += (numeric2[x1][x2][x3]* test4);
else
scoreTotal += (numeric2[x1][x2][x3]* final_test);
}
numeric2[x1][x2][5] = scoreTotal; // final numeric grade
scoreTotal = 0;
if(x2 >=courseSize)
break;
if((numeric2[x1][x2][5] > maxGrade) || (numeric2[x1][x2][5] <
minGrade) )
{
cout << "Error in calculating grade. Please fix the issue
then rerun the program. ignore broken program!";
cout << endl << endl;
continue;
}
else if(numeric2[x1][x2][5] >= letterGrade_A)
lettergrades[x1][x2] = 'A';
else if(numeric2[x1][x2][5] >= letterGrade_B)
lettergrades[x1][x2] = 'B';
else if(numeric2[x1][x2][5] >= letterGrade_C)
lettergrades[x1][x2] = 'C';
else if(numeric2[x1][x2][5] >= letterGrade_D)
lettergrades[x1][x2] = 'D';
else
lettergrades[x1][x2] = 'F';
}
}
for(int a1=0; a1< studsize; a1++)
{ fout << nonNumerical[a1][0]<< endl;
fout << right << setw(35) << "Name of Student:\t";
fout << nonNumerical[a1][1] << endl;
fout << right << setw(35) << "Student ID:\t";
fout << nonNumerical[a1][2]<< endl;
fout << right << setw(35) << "Address:\t" ;
fout << nonNumerical[a1][3] << endl;
fout << right << setw(35) << "Telephone Number:\t";
fout << nonNumerical[a1][4] << endl;
fout << right << setw(35) << "Student Soc. Security:\t";
fout << nonNumerical[a1][5] << endl;
fout << right << setw(35) << "Age:\t";
fout << numeric1[a1][0] << endl;
fout << right << setw(35) << "Number of years at Texas State:\t";
fout << numeric1 [a1][1] << endl << endl;
for(int b1=0; b1 <courseSize; b1++)
{
fout << right << setw(35) << "Course number:\t";
fout << nonNumerical[a1][(b1+6)] << endl;
for(int c1= 0; c1 <(examSize-1); c1++)
{
fout << right << setw(32) << "Exam #" << (a1 +1) << ":\t";
fout << numeric2[a1][b1][c1] << endl;
}
fout << right << setw(35) << "Numerical grade:\t";
fout << numeric2[a1][b1][5] << endl;
fout << right << setw(35) << "Letter grade:\t";
fout << lettergrades[a1][b1] << endl;
if( numeric2[a1][b1][5] < 70)
{
fout << right << setw(14) << " Warning Note: Your grade is too low
and needs improvements!" << endl << endl;
}
else if ( numeric2[a1][b1][5] >= 95)
{
fout << right << setw(14) << " Appreciation Note: Congratulations,
Your performance is Excellent!" << endl << endl;
}
else
fout << endl;
}
fout << endl;
}
inputFile.close();
fout.close();
return 0;
}
Instead of using array
std::string nonNumerical[studsize][strSize];
use std::vector.
std::vector<std::vector<std::string>> nonNumerical(studsize, std::vector<std::string(strSize));
Then, you can divide your code into as many functions as you need and pass the vectors to the functions.
void function1(std::vector<std::vector<std::string>>& nonNumerical)
{
...
}
and use it from main as:
int main()
{
...
std::vector<std::vector<std::string>> nonNumerical(studsize, std::vector<std::string(strSize));
...
function1(nonNumerical);
...
}
first of all c++ send arrays by reference .
your question is not clear ... but if I have get it right, you should send two dimensional arrays like this :
void f1(int a[][20]) ;
just the point is that , you must specify second dimension .
You can pass any size and dimension of array with pointers like this:
myfunction1(string *nonNumerical)
{
string something=nonNumerical[0][0];
}
But don't forget: You can't ask the array's size directly. You must pass the size with the array somehow.

"hour" counter won't reset, after the program is run again

I can't figure out how to reset the "hour" counter.
The program runs perfect on the 1st run, but when user enters another set of hours, hours start numbering between 110-117.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const float initialVolume = 130.00;
const float decreaseRate = 0.13;
int counter = 0;
int main()
{
int hours,i,j,k;
float remainingVolume, halfVolume, zeroVolume;
while (cout << "Enter hours to see how much caffeine "
<< "is left in your body, after you drank your coffee: " && cin >> hours)
{
cout << endl;
cout << fixed << showpoint << setprecision(4);
remainingVolume = initialVolume;
for (i = 0; i < hours; i++)
{
counter++;
remainingVolume = remainingVolume - decreaseRate * remainingVolume;
cout << "Hour " << setw(5) << counter << setw(15) << remainingVolume << "mg"<< endl;
}
for (j = 0, halfVolume = 130.00; halfVolume > 65.0000; j++)
{
counter++;
halfVolume = halfVolume - decreaseRate * halfVolume;
}
for (k = 0, zeroVolume = 130.00; zeroVolume > 0.0001; k++)
{
counter++;
zeroVolume = zeroVolume - decreaseRate * zeroVolume;
}
cout << "\n" << endl;
cout << "It will take " << j << " hours to get caffeine levels to 65mg. \n" << endl;
cout << "It will take " << k << " hours to get caffeine levels to 0mg. \n\n" << endl;
}
return 0;
}
output:
Enter hours to see how much caffeine is left in your body, after you
drank your coffee: 4
Hour 1 113.1000mg
Hour 2 98.3970mg
Hour 3 85.6054mg
Hour 4 74.4767mg
Enter hours to see how much caffeine is left in your body, after you
drank your coffee: 3
Hour 112 113.1000mg
Hour 113 98.3970mg
Hour 114 85.6054mg
You are never resetting your counter value. You initialise it to 0 and then increase it in every loop. you need to reset it to 0 every time they enter a new number (ie in your while loop).
The best solution would be to have to counter variable as a local variable declared in the loop:
while (cout << "Enter hours to see how much caffeine "
<< "is left in your body, after you drank your coffee: " && cin >> hours)
{
int counter=0;
cout << endl;
cout << fixed << showpoint << setprecision(4);
remainingVolume = initialVolume;
for (i = 0; i < hours; i++)
{
counter++;
remainingVolume = remainingVolume - decreaseRate * remainingVolume;
cout << "Hour " << setw(5) << counter << setw(15) << remainingVolume << "mg"<< endl;
}
for (j = 0, halfVolume = 130.00; halfVolume > 65.0000; j++)
{
counter++;
halfVolume = halfVolume - decreaseRate * halfVolume;
}
for (k = 0, zeroVolume = 130.00; zeroVolume > 0.0001; k++)
{
counter++;
zeroVolume = zeroVolume - decreaseRate * zeroVolume;
}
cout << "\n" << endl;
cout << "It will take " << j << " hours to get caffeine levels to 65mg. \n" << endl;
cout << "It will take " << k << " hours to get caffeine levels to 0mg. \n\n" << endl;
}
return 0;
}
You need to reset the counter after you're done with your iteration:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const float initialVolume = 130.00;
const float decreaseRate = 0.13;
int counter = 0;
int main()
{
int hours,i,j,k;
float remainingVolume, halfVolume, zeroVolume;
while (cout << "Enter hours to see how much caffeine "
<< "is left in your body, after you drank your coffee: " && cin >> hours)
{
cout << endl;
cout << fixed << showpoint << setprecision(4);
remainingVolume = initialVolume;
for (i = 0; i < hours; i++)
{
counter++;
remainingVolume = remainingVolume - decreaseRate * remainingVolume;
cout << "Hour " << setw(5) << counter << setw(15) << remainingVolume << "mg"<< endl;
}
for (j = 0, halfVolume = 130.00; halfVolume > 65.0000; j++)
{
counter++;
halfVolume = halfVolume - decreaseRate * halfVolume;
}
for (k = 0, zeroVolume = 130.00; zeroVolume > 0.0001; k++)
{
counter++;
zeroVolume = zeroVolume - decreaseRate * zeroVolume;
}
cout << "\n" << endl;
cout << "It will take " << j << " hours to get caffeine levels to 65mg. \n" << endl;
cout << "It will take " << k << " hours to get caffeine levels to 0mg. \n\n" << endl;
counter = 0; // <--
}
return 0;
}

Lining columns up

Solved!
This is what I wrote:
cout << setw(4) << "Students";
cout << setw(20) << "Hours Worked";
cout << setw(20) << "of Total Hours";
cout << endl;
for (int i = 0; i < students; i++)
{
cout << setw(20);
cout << names[i];
cout << setw(10) << hours[i];
cout << setw(10) << percent[i];
cout << endl;
}
But if the first name is a few characters sorter or bigger than second name, they become misaligned. How would I keep each column aligned equally?
Try something like this:
#include<iostream>
#include <iomanip>
#include<string>
using namespace std;
int main()
{
int students = 5;
string names[5] = {"a","bccc","c","d","ecsdfsdfasdasasf"};
int hours[5] = {1,2,3,4,5};
int percent[5] = {10,20,30,40,54};
string column("Students");
int maxStringSize = 0;
int sizeOfStudentColumn = column.length();
for(int i = 0; i < 5; ++i)
{
if(maxStringSize < names[i].length())
maxStringSize = names[i].length();
}
if(sizeOfStudentColumn > maxStringSize)
maxStringSize = sizeOfStudentColumn;
cout<<"max size: "<<maxStringSize<<endl;
cout << setw(4) << "Students";
cout << setw(maxStringSize + 5) << "Hours Worked";
cout << setw(20) << "of Total Hours";
cout << endl;
for (int i = 0; i < students; i++)
{
// cout << setw(20);
cout << names[i];
int diff = maxStringSize - names[i].length();
cout << setw(diff + 5 ) << hours[i];
cout << setw(20) << percent[i];
cout << endl;
}
}