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".
Related
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;
I'm new to coding. I wrote the below code in C++ and I am not allow to use array.
You will create a console C++ program that uses a nested loop to enter each archer's individual end scores and then displays the total score for each archer.
I am stuck at how to calculate the total end score:
#include <iomanip>
using namespace std;
int main()
{
int Rounds = 4;
int Archers = 3;
int endScore ;
int average;
for (int a = 1; a <= Archers ; a++)
{
cout << endl << "Number " << a << " score" << endl;
int tEndScore = 0 ;
for(int i=1; i <=Rounds ; i++)
{
cout << "Round " << i << " : " ;
cin >> endScore;
while(cin.fail())
{
cout << endl << "not enter an integer " << endl ;
cout << "Please enter an integer ";
cin >> endScore;
}
tEndScore += endScore;
}
cout << endl << "The total score for 4 ends of Archer Number " << a << " is " << tEndScore << endl;
average =(double) tEndScore/Rounds;
cout << setiosflags(ios::fixed) << setprecision(2) << endl << "The average score of 4 ends of Archer Number " << a << " is " << average << endl;
}
}
This is the result after running. It will only use the last value I entered as tEndScore:
You need to shift tEndScore =+ endScore; this line inside the second for loop as
for(int i=1; i <=Rounds ; i++)
{
...
...
tEndScore += endScore;
}
And it will be a good practice (And mandatory for your code...) to initialize the tEndScore for each player as
for (int a = 1; a <= Archers ; a++)
{
tEndScore = 0;
endScore = 0;
average = 0;
...
...
}
You need to replace totalEndScore to tEndScore and totalRounds to Rounds.
I was reading the chapter on structures in my book, and it got me re-modifying a program I already made, but this time using structures which I have never used before; however, after finishing the program, there's one issue I'm not understanding. The output of the program only displays once. It's in a for loop, and yet even though it asks me to input my information three times, it only outputs the first information.
I'm probably just not understanding how arrays in structures work.
An example of my issue is the following.
I have my output on the following loop
for(int counter = 0; counter <size; counter++)
The size is 3, which would mean I'll get the output printed three times; however the answer I'm getting is the same as if I was asking for the following.
Listofnames[0].F_name
When what I actually want is
Listofnames[0].F_name Listofnames[1].F_name Listofnames[2].F_name
However, I don't want to have to write it three times, I did to test it and it actually worked, but is that the only way to do it? Or did I miss something in my program?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Names
{
string F_name; //Creating structure called Names.
string L_name;
char Mi;
};
struct Payrate
{
double rate;
double hoursworked; //Creating structure called Payrate.
double gross;
double net;
};
int main()
{
double stateTax = 0, federalTax = 0, unionFees = 0, timeHalf = 1.5; //Initializing variables.
const int size = 2; //Array size.
Payrate employee[size]; //Structure variables
Names Listofnames[size];
for (int counter = 0; counter < size; counter++) //Initializing for loop.
{
cout << "What's your first name?: " << endl;
cin >> Listofnames[counter].F_name;
cout << "What's your last name?: " << endl; //Displaying names, and hours worked, rate.
cin >> Listofnames[counter].L_name;
cout << "What is your middle initial?: " << endl;
cin >> Listofnames[counter].Mi;
cout << "How many hours did you work? Please enter a number between 1-50: " << endl;
cin >> employee[counter].hoursworked;
cout << "What is your hourly rate? Please enter a number between 1-50: " << endl;
cin >> employee[counter].rate;
if (employee[counter].hoursworked < 0 || employee[counter].hoursworked >50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].rate < 0 || employee[counter].rate > 50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].hoursworked <= 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * employee[counter].rate; //Calculating gross.
}
else if (employee[counter].hoursworked > 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * (employee[counter].rate * timeHalf); //Calculating gross.
}
stateTax = employee[counter].gross * 0.06;
federalTax = employee[counter].gross * 0.12; //Calculates all the tax fees, and net.
unionFees = employee[counter].gross * 0.02;
employee[counter].net = employee[counter].gross - (stateTax + federalTax + unionFees);
}
cout << "FirstN " << "MI " << "LastName " << "\t" << "Rate " << "HoursWorked " << "TimeHalf " << "StateTax " << "FederalTax " << "UnionFees " << "Gross " << " " << "Net " << endl; //Displays header of output.
cout << "==================================================================================================================" << endl;
for (int counter = 0; counter <= size; counter++)
{
//Output.
cout << Listofnames[counter].F_name << "\t" << fixed << setprecision(2) << Listofnames[counter].Mi << " " << Listofnames[counter].L_name << "\t" << employee[counter].rate << "\t" << employee[counter].hoursworked << "\t" << setw(7) << timeHalf << "\t" << setw(8) << stateTax << setw(12) << federalTax << "\t" << unionFees << "\t" << employee[counter].gross << "\t" << employee[counter].net << endl;
system("pause");
}
}
P.s If you had to re modify this program again, what would you use to simplify it. Asking so I can keep re-modifying, and learn more advanced stuff. Vectors, pointers? Thanks in advance.
You have an array with 3 indexes but your loop is only going upto 2 indexes. Change your for loop to this.
for (int counter = 0; counter <= size; counter++)
Now, this loop will print the all the indexes.
Instead of using a static value you can also use this.
for (int counter = 0; counter < sizeof(Listofnames)/sizeof(Listofnames[0]); counter++)
sizeof(Listofnames)/sizeof(Listofnames[0]) This will give you the total size of your array.
Ideone Link
when I run this program is a "Run-Time Check Failure #2 stack around the variable 'numGrades' was corrupted" appears. Also the lowest grade doesn't output the correct answer. Any help would be greatly appreciated!
#include <iostream> // cin, cout
using namespace std;
const int TEN_GRADES = 10; // pre-defined number of grades
int main()
{
int numGrades[10];
double avg, highest = numGrades[0], lowest = numGrades[0], less, greater, grades;
double sum = 0;
// greeting message
cout << "---------------------------------" << endl
<< " Sandro's Statistics Generator " << endl
<< "---------------------------------" << endl << endl;
// requesting number of grades
cout << "Hello Professor, how many grades do I need to analyse this time? ";
cin >> numGrades[10];
if (numGrades[1] == 0)
{
cout << "\nGuess you changed your mind!!!" << endl
<< "Ending program now..." << endl << endl;
return 0;
}
// if user doesn't enter 0 user is ready to begin
cout << "Okay, I am ready. Start..." << endl;
for (int count = 0; count < numGrades[10]; count++)
{
cin >> numGrades[count];
sum += numGrades[10];
}
// to get the average
avg = sum / TEN_GRADES;
// to get the highest and lowest mark
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] > highest)
highest = numGrades[count];
}
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] < lowest)
lowest = numGrades[count];
}
// output requested statistics
cout << "Here are the requested stats for the " << numGrades << " grades." << endl
<< "The class average is " << avg << endl
<< "The highest grade is " << highest << endl
<< "The lowest grade is " << lowest << endl;
return 0;
}
Oh god, I don't even do c++ but I think one of my eyes bled a little.
Please review (or tell whoever coded this to review) how to create and assign values to them.
Then review simple data structures (like arrays) and loops.
One good way to start is to analyze the following WORKING code of your program:
Please mark as correct if it helps, and if you have any questions... Cheers!
#include <iostream>
#include <string>
using namespace std;
const int TEN_GRADES = 10; // pre-defined number of grades
int main()
{
int numGrades[10];
double avg, highest = 0, lowest = 0, less, greater, grades;
double sum = 0;
// greeting message
cout << "---------------------------------" << endl
<< " Newbie Statistics Generator " << endl
<< "---------------------------------" << endl << endl;
// requesting number of grades
cout << "Hello Professor, please enter 10 grades: "<<endl;
//THIS PART: loops ten times to input the grades
for (int count = 0; count < TEN_GRADES; count ++)
{
cout << "Grade number "<<count<<":";
cin >> numGrades[count];
}
//I get what you want to do here, but consider adding another exit condition here, what if the second grade is really 0 ?
if (numGrades[1] == 0)
{
cout << "\nGuess you changed your mind!!!" << endl
<< "Ending program now..." << endl << endl;
return 0;
}
// if user doesn't enter 0 user is ready to begin
cout << "Okay, I am ready. Start..." << endl;
for (int count = 0; count < TEN_GRADES; count++)
{
sum += numGrades[count];
}
// to get the average
avg = sum / TEN_GRADES;
// to get the highest and lowest mark
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] > highest)
highest = numGrades[count];
}
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] < lowest)
lowest = numGrades[count];
}
// output requested statistics
cout << "Here are the requested stats for the " << TEN_GRADES << " grades." << endl
<< "The class average is " << avg << endl
<< "The highest grade is " << highest << endl
<< "The lowest grade is " << lowest << endl;
return 0;
}
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.