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

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;
}

Related

How to use one-dimension array in c++ to display a survey responses by count and percentage?

The question goes like this...
"Thirty students were asked to rate the quality of the food in the student cafeteria on a
scale of 1 to 5 (1=poor, 2=fair, 3=neutral, 4 =good, and 5=excellent). Write a C++ program that stores 45 responses into a one-dimensional array and gives a summary of each case in terms of count and percentage"
I have already written a program and it runs, however, I think it is very long and I am having trouble finding an alternative.
#include <iostream>
using namespace std;
int main()
{
int count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
// int count=0;
int rate[45];
for (int i = 0; i < 45; i++) {
cout << "Please rate the school's food on 1-5 scale" << endl;
cin >> rate[i];
}
for (int i = 0; i < 45; i++) {
cout << i + 1 << "." << rate[i] << endl;
}
for (int i = 0; i < 45; i++) {
if (rate[i] == 1) {
count1 = count1 + 1;
}
if (rate[i] == 2) {
count2 = count2 + 1;
}
if (rate[i] == 3) {
count3 = count3 + 1;
}
if (rate[i] == 4) {
count4 = count4 + 1;
}
if (rate[i] == 5) {
count5 = count5 + 1;
}
}
cout << "------------SUMMARY--------------" << endl;
cout << "Students who rated:" << endl;
cout << "The school's food deserves a 1: " << count1 << " " << (count1 * 100) / 45 << "% of the students" << endl;
cout << "The school's food deserves a 2: " << count2 << " " << (count2 * 100) / 45 << "% of the students" << endl;
cout << "The school's food deserves a 3: " << count3 << " " << (count3 * 100) / 45 << "% of the students" << endl;
cout << "The school's food deserves a 4: " << count4 << " " < (count4 * 100) / 45 << "% of the students" << endl;
cout << "The school's food deserves a 5: " << count5 << " " << (count5 * 100) / 45 << "% of the students" << endl;
cout << "-------------END OF SUMMARY----------" << endl;
return 0;
}
Is there an easier way to do it?
I appreciate any help,
Thank you.
Disclaimer: I am a beginner in c++

Algorithm to partition an array of N elements into K parts where the difference between the sums of elements is minimal

I need to write an algorithm to optimally partition an array of N elements into K parts where the difference between the sums of the elements in each part is minimal (where all of the parts are as equivalent to one another as possible). The order of elements in the array must not be reordered. I need to find the array indices that will result in the optimal partition.
I have seen similar problems posted here, but none quite as abstract and complicated. I am currently taking a C++ algorithms class, but this is for a personal/side project, not any sort of assignment.
Here's some very rough starter code that attempts to use recursion to partition the array and even out the partitions, but the result is far from optimal, and I'm not even sure I'm on the right track. I'm guessing there's a far better algorithm out there somewhere. Any guidance would be appreciated.
#include <iostream>
#include <fstream>
#include <vector>
#include <limits>
using namespace std;
void books(ifstream&);
void calculate(vector<int>&, vector<string>&, int, int, int, int, bool&, int&);
int main(int argc, const char * argv[]) {
vector<int> list;
vector<string> days;
int num;
ifstream fin("list.txt");
while(fin >> num) {
list.push_back(num);
}
fin.close();
int wordsPerBook = 0;
for (auto i : list) {
wordsPerBook += i;
cout << i << " ";
}
cout << endl;
int numDays = 8;
int wordsPerDay = wordsPerBook / numDays;
cout << "wordsPerBook: " << wordsPerBook << endl;
cout << "wordsPerDay: " << wordsPerDay << endl << endl;
int start = 0, day = 1;
int minOverPlus1Error = INT_MAX;
bool extraDay = false;
calculate(list, days, start, day, numDays, wordsPerDay, extraDay, minOverPlus1Error);
cout << endl << "Days: " << endl;
for (auto i : days)
cout << i << endl;
cout << endl;
if (extraDay && day == 1) {
extraDay = false;
cout << endl << "*********************Re-Calculate*********************" << endl;
days.clear();
days.shrink_to_fit();
calculate(list, days, 0, day, numDays, wordsPerDay, extraDay, minOverPlus1Error);
}
cout << endl << "Days: " << endl;
for (auto i : days)
cout << i << endl;
cout << endl;
if (extraDay && day == 1) {
extraDay = false;
cout << endl << "*********************Re-Calculate*********************" << endl;
days.clear();
days.shrink_to_fit();
calculate(list, days, 0, day, numDays, wordsPerDay, extraDay, minOverPlus1Error);
}
cout << endl << "Days: " << endl;
for (auto i : days)
cout << i << endl;
cout << endl;
return 0;
}
void calculate(vector<int>& list, vector<string>& days, int start, int day, int numDays, int wordsPerDay, bool& extraDay, int& minOverPlus1Error) {
int sumUnder = 0, sumOver = 0, sumUnderMinus1 = 0, sumOverPlus1 = 0;
int nextStart = 0, words = 0;
cout << "day: " << day << endl;
if (day > numDays) {
extraDay = true;
return;
}
if (start >= list.size() - 1)
return;
for (int i = start; i < list.size() - 1; i++) {
if (sumOver < wordsPerDay) {
cout << list[i] << " ";
sumUnder += list[i];
if (i + 1 < list.size())
sumOver = sumUnder + list[i + 1];
else
sumOver = sumUnder;
if (i - 1 >= 0)
sumUnderMinus1 = sumUnder - list[i - 1];
else
sumUnderMinus1 = sumUnder;
if (i + 2 < list.size())
sumOverPlus1 = sumOver + list[i + 2];
else
sumOverPlus1 = sumOver;
nextStart = i + 1;
}
if (minOverPlus1Error == sumOverPlus1 - wordsPerDay) {
sumOver = sumOverPlus1;
sumOverPlus1 = sumOverPlus1 + list[i + 3];
}
else if (minOverPlus1Error == sumOverPlus1 + list[i + 3] - wordsPerDay) {
sumOver = sumOverPlus1 + list[i + 3];
sumOverPlus1 = sumOverPlus1 + list[i + 3] + list[i + 4];
}
}
if (minOverPlus1Error == sumOver - wordsPerDay) {
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
words = sumOver;
minOverPlus1Error = INT_MAX;
}
else if (minOverPlus1Error == sumOver - wordsPerDay) {
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
cout << list[nextStart] << " ";
nextStart += 1;
words = sumOver;
minOverPlus1Error = INT_MAX;
}
else if ((wordsPerDay - sumUnder) > (sumOver - wordsPerDay)) {
cout << list[nextStart] << " ";
nextStart += 1;
words = sumOver;
}
else
words = sumUnder;
days.push_back("Day " + to_string(day) + ": Chs " + to_string(start + 1) + "-" + to_string(nextStart) + " Words: " + to_string(words));
cout << endl << "nextStart: " << nextStart << endl;
cout << "sumUnder: " << sumUnder << " error: " << wordsPerDay - sumUnder << endl;
cout << "sumOver: " << sumOver << " error: " << sumOver - wordsPerDay << endl;
cout << "sumUnderMinus1: " << sumUnderMinus1 << " error: " << wordsPerDay - sumUnderMinus1 << endl;
cout << "sumOverPlus1: " << sumOverPlus1 << " error: " << sumOverPlus1 - wordsPerDay << endl << endl;
calculate(list, days, nextStart, day + 1, numDays, wordsPerDay, extraDay, minOverPlus1Error);
if (extraDay && minOverPlus1Error > sumOverPlus1 - wordsPerDay) {
minOverPlus1Error = sumOverPlus1 - wordsPerDay;
cout << "minOverPlus1Error: " << minOverPlus1Error << endl;
}
}```

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".

Dice game that requires us to number our turns along with adding * before every dice roll

visit http://voyager.deanza.edu/~bentley/ass5.html
My goal is trying to match the sample output that is on the link. The only obstacles that I can not seem to overcome is how to add what turn you are on and also "*" before each line dice roll.
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int roll();
int turn();
int main ()
{
srand(time(0));
int gameTotal = 0;
while (gameTotal < 100)
{
gameTotal += turn();
cout << "Your total is now " << gameTotal << endl << endl;;
}
}
int turn()
{
int turnTotal = 0;
int temp;
for (int i = 0; i < 3; i++)
{
temp = roll();
if (temp == 7) break;
turnTotal += temp;
}
cout << "You scored " << turnTotal << " points for this turn" << endl;
return turnTotal;
}
int roll()
{
int die1 = rand() % 6 + 1;
int die2 = rand() % 6 + 1;
int sum = die1 + die2;
cout << "You rolled a " << die1 << " and " << die2 << ". " << "That's " << sum << endl;
return sum;
}
Just add a variable to store the number of turns played and update it at every turn. adding the * is even simplier:
int main ()
{
srand(time(0));
int gameTotal = 0;
int turns = 0;
while (gameTotal < 100)
{
// update number of turns and output it
++turns;
cout << "This is your turn #" << turns << endl;
gameTotal += turn();
cout << "*** Your total is now " << gameTotal << endl << endl;
// ^^^ easy
}
}
Similar changes in the other functions:
cout << "** You scored " << turnTotal << " points for this turn" << endl;
// ^^
and
cout << "* You rolled a " << die1 << " and " << die2 << ". " << "That's " << sum << endl;
// ^

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;
}
}