I was writing a piece of software that allows to the user to compute the average of ten integer numbers. This is the code:
// Algorithm for computing the average of the grades of a class with the controlled iteration of a counter
#include <iostream>
using namespace std;
int main()
{
int total, // sum of all grades
gradeCounter, // n° of inputted grades
grade, // a single vote
average; // average of grades
// initialization phase
total = 0; //sets the total to zero
gradeCounter = 1; //prepares the counter
// elaboration phase
while ( gradeCounter <= 10 ) { // 10 times cycle
cout << "Enter grade: "; // input prompt
cin >> grade; // input grade
total = total + grade; // adds the grade to the total
gradeCounter = gradeCounter + 1; // increases the counter
}
// end phase
average = total / gradeCounter;
cout << "The class average is " << average << endl;
return 0;
}
Now, I was thinking that writing average = total / gradeCounter; would work, since the last variable stored in gradeCounter is 10; but the result given by average = total / 10; is the real average. I don't get why there's this discrepancy.
Can somebody explain this to me?
Actually what is happening is that after each run of your while loop, the value of gradeCounter is 1 more than the number of times the loop has been run(because you have initialized gradeCounter to 1 before start of the loop). You can do any 1 of the following to fix this.
1)
average = total / (gradeCounter-1);
2)
gradeCounter = 0;
while ( gradeCounter < 10 ) {
cout << "Enter grade: ";
cin >> grade;
total = total + grade;
gradeCounter = gradeCounter + 1;
}
while ( gradeCounter <= 10 ) { //10 times cycle
cout << "Enter grade: "; //input prompt
cin >> grade; //input grade
total = total + grade; //adds the grade to the total
gradeCounter = gradeCounter + 1; //increases the counter
}
In this piece of code, when gradeCounter is 10, the while loop runs once more, incrementing gradeCounter to 11. So later, you're really dividing by 11 rather than 10.
while ( gradeCounter <= 10 )
This condition evaluates to false when, in your case, gradeCounter is incremented to 11.
(11 is not less or equal to 10)
So your counter is eleven, not ten after your loop.
while ( gradeCounter <= 10 ) { //10 times cycle
gradeCounter = gradeCounter + 1;
Grade counter will be 11 after the loop ends (last iteration it gets set to 11, then <= 10 is not true and it exits. So you'd be doing a divide by 11 instead of 10.
You should draw a flowchart for this. If gradeCounter <= 10, you go into the loop, and only when gradeCounter >= 11 do you proceed with average = total/gradeCounter
That's why you get a result divided by 11 instead of 10.
Related
I want to calculate the approx of pi with Viete's formula of nested square roots of 2
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int k; //variable for user input
int n = 1; //built integer that causes the program to loop
double result;
//greeting message, start of program
cout << "Welcome to the Approx PI program.\n";
cout << "Please enter in a value for k...\n";
cin >> k;
//if user inputs a number outside the interval
while (k < 1 || k > 30)
{
cout << "Invalid ---k must be >=1 and <=30\n";
cout << "Please enter in a value for k...\n";
cin >> k;
}
//calculating PI with the nested square root formula
while (n <= k - 1)
{
result = sqrt(2 + result);
n++;
}
result = pow(2, k) * sqrt(2 - result);
//outputs the result, end of program
cout << "Approx PI = " <<setprecision(20)<<fixed<<result<<endl;
return 0;
}
But when I enter 28, it gives me 4:
Welcome to the Approx PI program.
Please enter in a value for k...
28
Approx PI = 4
Process finished with exit code 0
When I enter 29 or 30, the result is 0:
Welcome to the Approx PI program.
Please enter in a value for k...
30
Approx PI = 0
Process finished with exit code 0
I think k=30 should be giving me:
Approx PI = 3.14245127249413367895
What am I doing wrong?
When you declare result, you should assign it some value. Otherwise, you cause undefined behaviour because at line 25 you use the uninitialised memory result.
I am having to create a program that reads from the user what time they entered a parking garage and what time they left. The program uses this information to then figure out how much it costed the person to park there. For under 30 minutes, it's free. After 30 minutes and up to 2 hours, it is a $3 base charge, plus 5 cents every minute in excess of 30 minutes. Beyond 2 hours, it is an $8 base charge, plus 10 cents every minute in excess of 2 hours. I have so far got to convert the time the user inputted into all minutes. I am now stuck on what to do for the rest of my functions. I am new to programming, and the arguments in a function still confuse me. If you are able to help or provide any feedback, please tell in the comment section how the arguments were implemented to get the code to run correctly. Here is my code thus far:
#include <iostream>
using namespace std;
int elapsed_time(int entry_time, int exit_time)
{
int total = 0;
total = (exit_time / 100) * 60 + (exit_time % 100) - (entry_time / 100) * 60
+ (entry_time % 100);
return total;
} // returns elapsed time in total minutes
double parking_charge(int total_minutes) {
double total = 0;
double cents = 0;
if(total_mins < 30){
return 0;
}
else if (total_mins <= 120){
cents = (total_mins - 30) * 0.05;
return total = 3 + cents;
}
else{
cents = (total_mins - 120) * 0.10;
return total = 4.5 + 8 + cents;
}
} // returns parking charge
void print_results(total_minutes, double charge)
{
cout << "The charge of parking was: " << parking_charge(total_minutes)
}
int main() {
int entry_time = 0;
int exit_time = 0;
cout << "What was the entry time? (Enter in 24 hour time with no colon) ";
cin >> entry_time;
cout << "What was the exit time? (Enter in 24 hour time with no colon) ";
cin >> exit_time;
cout << print_results(total_minutes, charge);
}
I have updated my code with a working parking charge function. I am now aiming to get the print_results function working correctly and finding out how to get all of this to work together in the main function. Thanks to all for the help so far.
Your are almost done, You have need to call functions properly in main function. Declare two variables in main function totalTime and totalChargethen call the function
#include <iostream>
using namespace std;
int elapsed_time(int entry_time, int exit_time)
{
int total = 0;
total = (exit_time / 100) * 60 + (exit_time % 100) - (entry_time / 100) * 60
+ (entry_time % 100);
return total;
} // returns elapsed time in total minutes
double parking_charge(int total_minutes)
{
int charge;
if (total_minutes <= 30)
charge = 0;
else if (120 > total_minutes < 30)
charge = (3 + (0.05 * total_minutes));
else
charge = (8 + (0.10 * total_minutes));
} // returns parking charge
void print_results(double charge)
{
cout << "The charge of parking was: " << charge;
}
int main()
{
double charge,minutes;
int entry_time,exit_time;
cout << "What was the entry time? (Enter in 24 hour time with no colon) ";
cin >> entry_time;
cout << "What was the exit time? (Enter in 24 hour time with no colon) ";
cin >> exit_time;
minutes=elapsed_time(entry_time,exit_time);
charge=parking_charge(minutes);
print_results( charge);
}
A given file contains pairs of . Then take a toss-up two-digit number (called X), and compute the win/loss amount. The win/loss rule is if the input number matches X, then it’s a win and the winning total is (amount * 70); otherwise, it’s a loss of (-amount).
For example: [ticket.txt]
09 10
13 15
25 21
If the toss-up number is 09, the win/loss amount of the ticket is (10 * 70 - 15 - 21 = 664)
If the toss-up number is 42, the win/loss amount of the ticket is (-10 - 15 - 21 = -46).
While reading file by arrays has a fixed size. What I mean is that what if the file ticket.txt doesn't have specific size. Can someone help me to change reading file by array to vector or something else doesn't have fixed size.
For example: [ticket.txt]
09 10
13 15
25 21
.. ..
#include <iostream>
#include <fstream>
using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
int winNum, winAmount = 0, lostAmount = 0, result = 0;
int num = 0; // num start at 0
ifstream inFile;
inFile.open("Ticket.txt"); //open File
if (inFile.fail())
{
cout << "Fail to open the file" << endl;
return 1;
}
int myArray[3][2];
for(int i = 0; i < 3; i++)
for(int j = 0; j < 2; j++)
inFile >> myArray[i][j];
cout << "Numbers from File: " << endl;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
{
cout << myArray[i][j] << " ";
}
cout << "\n";
}
cout << endl;
cout << "Enter the toss-up number: "; // enter the win number
cin >> winNum;
for(int i = 0; i< 3;i++)
{
if (myArray[i][0] == winNum)
{
winAmount = myArray[i][1] * 70; // number user choose = win number, winAmount = winAmount * 70 - lostAmount
}
else
{
lostAmount = lostAmount + myArray[i][1]; //number user choose != win number, the amount will be -lost amounts
}
}
result = winAmount - lostAmount;
cout << result;
cout << endl << endl;
system("pause");
return 0;
}
There are a bunch of different ways to approach this problem.
One could make a vector of vectors
std::vector<std::vector<int>> myArray;
but this is pretty wasteful. Only the inner dimension is variable in size, so a quick improvement is
std::vector<std::array<int, 2>> myArray;
Loading myArray can be pretty simple, depending on how much verification you want to include. Here it is with minimal verification:
int number,amount;
while (inFile >> number >> amount)
{
myArray.push_back({number,amount});
}
This will loop until two ints can't be read, be it because of the end of the file or garbage in the file. It is also easily fooled by a file with the worn number of columns . Better approaches use std::getline to get whole lines and make sure exactly two valid numbers and nothing else is on each line.
The rest of your code is unchanged.
But there may be a better way to do this, Consider
a) The loss amount never changes. You can precompute it and eliminate the loop in the event of a loss.
b) Extending on that, you can eliminate part of the loop on a win. The loss amount contains the winning number use the loss amount minus the winning amount. In other words,
winnings = amount * 70 - (loss - amount)
Which is the same as
winnings = amount * 70 - loss + amount
or
winnings = amount * 71 - loss
So we can stop looking as soon as we find a win and only do one calculation.
c) We can eliminate any need for a look-up loop with a std::map.
Reading in the file into a std::map is similar:
std::map<int, int> myMap;
int number,amount;
int loss = 0;
while (inFile >> number >> amount)
{
myMap[number] = amount; // map the amount to the number
loss += amount;
}
and look-up is something like
int result = 0;
auto found = myMap.find(winNum); // look in the map for a number
if (found != myMap.end()) // number is in the map
{
result = 71* found->second; // take the winnings plus one extra to counterbalance
// number's addition to the losses
}
result -= loss; //remove the loss
The calculation loop is completely eliminated and less code is almost always better. Code that's not there has zero bugs. Unless it not being there IS a bug, but that's a different problem.
Note: For small files this approach will be SLOWER. std::map has a much lower time complexity than iterating a std::vector, but each of those iterations it has to perform can be much more expensive.
Documentation on std::array
Documentation on std::vector
Documentation on std::map
Can someone please look at this code and help me figure out what's wrong?
#include <iostream>
#include <vector>
using namespace std;
int numExercise;
cout << "Enter num exercises: ";
cin >> numExercise;
vector <float> weight;
float sumWeight = 0;
while(sumWeight != 1)
{
// Loop to assign a weighted value to each exercise.
for ( int i = 0; i < numExercise; i++ )
{
float weightEntered;
cout << "\n Assignment " << i + 1 << " : ";
cin >> weightEntered;
//Divide percentage by 100 to get decimals.
weightEntered /= 100;
//Send the data back to the vector.
weight.push_back( weightEntered );
}
// Loop to error check if the total weights isn't 100.
for ( int i = 0; i < numExercise; i++ )
{
sumWeight += weight[i];
}
cout << sumWeight << endl;
sumWeight = 0;
//if ( sumWeight != 1 )
cout << "\n\t\tError, total weights should be 100" << endl;
}
So in this code I'm entering a certain amount of assignments and the weights per assignment have to be over 100%... for example enter 3 assignments and each weight is 30, 30, 40. After the weight is entered the code divides each weight by 100 to get decimal values (I'm using that in the rest of my code to calculate something else).
The issue is that I'm trying to make sure that whatever the user enters add up to 100 otherwise they have to enter the numbers again. When I run this loop and enter the wrong numbers it asks me to enter them again but it doesn't go through the sum of the weights entered the second time, so the number displayed is still the first sum. What am I doing wrong??
You are using vector to store the weights,
Let say for three assignments, you entered 30,30,30. Now vector becomes { 30,30,30 } and you are summing over this vector from 0 to 2 index.
In next time, you entered 20,20,40. Now vector becomes {30,30,30,20,20,40} and you are summing over this vector again from 0 to 2 index.
You can solve your problem by using insert rather than push_back
Hi I'm needing some help. I'm in a intro to programming class and we are using c++. I am hoping someone can help me with an assignment that was due yesterday (I understand not to expect miracle responses but a girl can always try).
I'm having two problems that I know of. The first is regarding the smallest value.
The big one is in trying to make it loop for requirements of three times but not lose out on my total count. I cannot use arrays or anything I haven't learned yet which is why I've posted this. I've seen similar problems and questions but they have ended up with answers too complex for current progress in class. So here is the problems instructions:
Instructions
1) Write a program to find the average value, the largest value, and the smallest value of a set of numbers supplied as input from the keyboard. The number of values in the data set must be in the range 0 to 20, inclusive. The user will first enter the number of values in the data set(use variable int Number). Give the user 3 attempts at entering Number in the range given. If the value for Number entered is out of this range, write an error message but continue. If the user does not enter a valid value for Number within the 3 attempts print an error message and terminate the program.
2) Format only the output for the Average value to 3 decimal places when printed.
3) The values in the data set entered as input can be any value positive, negative, or zero.
4) Make the program output readable(see the example below). (Note: that you will notprint out the input values that were entered in this program like you normally are required to do. This is because we have not covered the “tool” needed to do so yet in our studies).
Below will be the output from the execution of your program:
(using these values in order for the data set --> 19.0 53.4 704.0 -15.2 0 100.0)
The largest number: 704
The smallest number: -15.2
The average of the 6 numbers entered: 143.533
yourName L4p2XX.cpp
Lab#4 prob 2 XX-XX-12
Here is my poor excuse at the solution:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double Number = 0, minValue, maxValue, average, total = 0;
int ct = 0, numCount;
cout << "How many numbers would you like to enter? ";
cin >> numCount;
for(ct = 1; ct <= numCount; ct += 1)
{
cout << "Enter Value from 0 to 20, inclusive: ";
cin >> Number;
if(Number > 20|| Number < 0)
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
{
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
total += Number;
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
} //end for loop
cout << "The smallest number entered was " << minValue << endl;
cout << "The largest number you entered was " << maxValue << endl;
average = total/numCount;
cout << setprecision(3) << fixed << showpoint << "You entered " <<
numCount << " numbers. The average of these is " << average;
//Program ID
cout <<"\n" << "L4P2LB.cpp\n" << "11-05-12\n";
system ("pause");
return 0;
} // End main
Thank you in advance to anyone who can steer me in the right direction. Not looking for anyone to do my work I just need help in direction if nothing else or any suggestions as to what to do. Thanks again. Lynda
Also I need somehow to pause after the third time and exit properly. If I put the second pause in it won't work so am I missing something obvious there too!
The first problem I see is that you didn't initialize a couple of variables.
You should either initialize both minValue and maxValue variables with something which will overwritten in every case in the first loop (typically "positive/negative infinity", as provided by <limits>), or just set both to Number in the first iteration, regardless of their current value. So I'd suggest to fix this by replacing
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
with
if(maxValue <= Number || ct == 1)
maxValue = Number;
if(Number <= minValue || ct == 1)
minValue = Number;
as ct == 1 will be true in the first iteration.
That said, you check the 0..20 range condition on the wrong variable. You check it on the Number variable, but you should check the numCount variable. But you also didn't respect the requirement that the variable to store the "number of numbers" should be Number, so you did check the correct variable, but used the wrong to read the input into. This should fix this issue (I changed the variable name in the cin >>... line + moved the check outside your main loop):
cout << "How many numbers would you like to enter? ";
cin >> Number;
if(Number > 20|| Number < 0)
{
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
...
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
}
for(ct = 1; ct <= Number; ct += 1)
{
...
}
...