I am trying to write a program that calculates students last scores as a midterm, quiz1, quiz2 and final then finds their class average depends on a number of students. Program will show the class average. User should enter the scores. I am new to c++, and my problem is right now i can't find a way to connect this for loop to an array for class average. Is my code wrong for this? I don't know what to do.
#include <iostream>
using namespace std;
int main()
{
int mt, q1, q2, fnl, stdn, num;
double cls[5], std, avg;
cout << "Enter a number of students: ";
cin >> num;
for (stdn=0; stdn<num; stdn++) {
cout<<"Enter mt, q1, q2, fnl of a "<<stdn+1<<". student in order:"<<endl;
cin>>mt>>q1>>q2>>fnl;
std = mt * 30/100 + q1 * 10/100 + q2 * 10/100 + fnl * 50/100;
cout<<stdn+1<<". students total score is "<<std<<endl;
}
}
Type int is always rounding down the value after a decimal point.
So, (int)3.84 == 3, and therefore your std variable will probably have a wrong value.
Define all variables as double for start. To calculate avg simply add marks then devide by the number of students in the end.
double mt, q1, q2, fnl, stdn, num, grades_sum = 0, avg;
...
for(stdn=0; stdn<num; stdn++){
...
grades_sum += mt * 30/100 + q1 * 10/100 + q2 * 10/100 + fnl * 50/100;
...
}
avg = grades_sum/num;
You don't need an array for class average. Just add up all the students scores and divide by the number of students. That just needs one variable (I've called it std_sum) not an array. Like this
double std_sum = 0.0;
for(stdn=0; stdn<num; stdn++){
...
std = mt * 30/100 + q1 * 10/100 + q2 * 10/100 + fnl * 50/100;
std_sum = std_sum + std; // add up all student scores
}
avg = std_total/num;
You can add up all of the students scores, then at the end divide by the total number of students. This will give you a total average of the class. Also, I avoided integer division by replacing your fractions with decimals that add up to 1. I also edited your for loop to start at 1 and go to the number, to avoid adding 1 to everything.
#include <iostream>
using namespace std;
int main()
{
int mt, q1, q2, fnl, stdn, num;
double cls[5], std;
double classAvg = 0; // add a new variable
cout << "Enter a number of students: ";
cin >> num;
for (stdn=1; stdn <= num; stdn++) {
cout << "Enter mt, q1, q2, fnl of a " << stdn << ". student in order:" << endl;
cin >> mt >> q1 >> q2 >> fnl;
std = (mt * 0.3) + (q1 * 0.1) + (q2 * 0.1) + (fnl * 0.5);
cout << stdn << ". students total score is " << std << endl;
classAvg = classAvg + std; // start adding the totals of all the students
}
avg = classAvg/num; // find the total average by dividing by total students
cout << "Class Average is " << classAvg << endl; // display average.
}
Related
This question already has an answer here:
Dividing two integers to produce a float result [duplicate]
(1 answer)
Closed 1 year ago.
Here i want to calculate the number of sweets that i have been sold in Day 2.
int main()
{
float rate;
int left, total, sell ;
cout << "rate" ; // the rate that sweets have been sold per day
cin >> rate;
cout << "sell"; // number of sweets that have been sold in day1.
cin >> sell;
cout << "total"; // total number that the shops originally have
cin >> total;
left = total - sell;
sell = sell*(1+rate*(left/total));
cout << sell;
return 0;
}
And i want to calculate the numbers of sweets that have been sold in day2.
Assume the input are rate = 0.5, sell=100, total = 10000.
The output should be 14950. [ 10000 * (1+0.5*((10000-100)/10000)) ]
But why I still get 10000 after running the program.
Updated:
However, I have one more question. If i want to output a rounded up sell value. How could I do it? because i am not allowed to change the datatype of the variables, which means it should be still int sell; at the initialization part. I have tried cout << round((double) sell); But it still does not work.
As mentioned in the comment, you are doing an integer division. Here is the corrected code:-
#include<iostream>
using namespace std;
int main()
{
float rate;
int left, total, sell ;
cout << "rate" ; // the rate that sweets have been sold per day
cin >> rate;
cout << "sell"; // number of sweets that have been sold in day1.
cin >> sell;
cout << "total"; // total number that the shops originally have
cin >> total;
left = total - sell;
sell = sell*(1+rate*(left/(float)total));
cout << sell;
return 0;
}
I have typecasted the denominator.
Every time I run the program, using the exact same values (25 for diameter and 5 for depth), I am getting different values for water_price and I'm not sure why.
Some of the outcomes:
$6.62256e+07 is the total cost.
$0 is the total cost.
$2.43411e-27 is the total cost.
I don't know if I am dealing with values in memory not playing well with each other, not flushing or what.
Why are the outcomes different every time I run this program?
#include <iostream>
#define PI 3.1416
#define WATER_COST 1.80
using std::cout;
using std::cin;
using std::endl;
int main() {
float pool_diameter, pool_depth;
float pool_radius = pool_diameter / 2;
float pool_volume_sq_inches = (PI * pool_radius * pool_radius * pool_depth) * 1728;
float pool_gallons = pool_volume_sq_inches / 231;
float water_price = (pool_gallons / 748) * WATER_COST;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
cout << "\n$" << water_price << " is the total cost." << endl;
return 0;
}
See how we need to declare the variables to begin with, then when you ask for input it will be stored in those variables, and then you can continue on with the calculations you need.
#include <iostream>
#define PI 3.1416
#define WATER_COST 1.80
using std::cout;
using std::cin;
using std::endl;
int main() {
float pool_diameter = 0.0;
float pool_depth = 0.0;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
float pool_radius = pool_diameter / 2;
float pool_volume_sq_inches = (PI * pool_radius * pool_radius * pool_depth) * 1728;
float pool_gallons = pool_volume_sq_inches / 231;
float water_price = (pool_gallons / 748) * WATER_COST;
cout << "\n$" << water_price << " is the total cost." << endl;
return 0;
}
You may want to get the inputs soon after the declaration.
float pool_diameter, pool_depth;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
Rest code would work the way it is.
A good practice would be to initialize your variables like Omid-CompSci has answered here.
Statement float pool_radius = pool_diameter / 2; is executed before
cin >> pool_diameter;. Default value(garbage value) is used every time to calculate the pool_radius that is reason for different values in different runs.
change the order.
Write a grading program for a class with the following grading policies:
a. There are two quizzes, each graded on the basis of 10 points.
b. There is one midterm exam and one final exam, each graded on the basis of
100 points.
c. The final exam counts for 50% of the grade, the midterm counts for 25%, and
the two quizzes together count for a total of 25%. (Do not forget to normalize
the quiz scores. They should be converted to a percentage before they are averaged
in.)
Any grade of 90 or more is an A, any grade of 80 or more (but less than 90) is a
B, any grade of 70 or more (but less than 80) is a C, any grade of 60 or more (but
less than 70) is a D, and any grade below 60 is an F. The program will read in the
student’s scores and output the student’s record, which consists of two quiz and
two exam scores as well as the student’s average numeric score for the entire course
and final letter grade. Define and use a structure for the student record.
#include <iostream>
#include <string>
using namespace std;
struct Report {
public:
};
int inputQuizzone ( int& Quizz1); //input functions take read in the input
int inputQuizztwo ( int& Quizz2); // user inputs result of quizz. Each quizz
// is 10 points
int inputMideterm ( int& MidExam);
int inputExam ( int& Finall);
double OutputQuizz ( int& Q1, int& Q2); // this is meant to calculate the
// by adding quizz 1 and quizz two to 25%
double Output ( int& Quizz);
double OutputMideterm ( int MidExam);
double OutputExam ( int& Final);
int main()
{
Report FinalGrade ;
int
x , y ,z , xz , gr;
inputQuizzone( x);
inputQuizztwo( y);
inputMideterm(z);
inputExam( xz);
cout << " Your Final Grades are " << '\n'
<< " Quizzes " << "" << OutputQuizz( x, y) << '\n'
//<< "Quizz Two " << Quizz2<< '\n'
<< " Mideterm " << OutputMideterm( z) << '\n'
<< " Finals " << OutputExam(xz) << endl;
}
int inputQuizzone ( int& Quizz1)
{
cout << " Enter Your Quizz One Score over 10"<< endl;
cin >> Quizz1;
}
int inputQuizztwo ( int& Quizz2)
{
cout << " Enter Your Second Quizz 2 Score over 10"<< endl;
cin >> Quizz2;
}
int inputMideterm ( int& MidExam)
{
cout << " Enter Your Midterm Score over 100"<< endl;
cin >> MidExam;
}
int inputExam ( int& Finall)
{
cout << " Enter Your Exam Score over 100"<< endl;
cin >> Finall;
return (Finall);
}
double OutputQuizz ( int& Q1, int& Q2)
{
int QR = 0;
QR = (((Q1 + Q2 ) / 20) * 25 ) ;
return (QR);
}
double OutputMideterm ( int MidExam)
{
int QR = 0;
QR = (MidExam / 100) * 25;
return (QR);
}
double OutputExam ( int& Final)
{
int QR = 0;
QR = (Final / 100) * 25;
return (QR);
}
Without looking at the way values are computed, the main issue is that, in your output functions, you are doing integer arithmetic to compute a value that is smaller than 1. For example, in OutputQuizz, (Q1 + Q2 ) / 20 will usually be less than 1.
To force the compiler to use floating point, use QR = (((Q1 + Q2 ) / 20.0) * 25.0 ) instead.
You will see values that are not 0.
I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100
Apparently there is a calculation error somewhere in my program, but I simply can’t find it.
The only information I have as to why there is a calculation error is this following feedback given by MyProgrammingLab (A site that automatically tests code to see if it's incorrect or not). I don't know what values were entered for the annual death rate and annual birth rate to cause it. Could it be that I'm right but MyProgrammingLab is wrong? Honestly, all my own tests seem fine.
Expected Output:
Year 1: 200 176
Year 2: 176 154
Year 3: 154 135
Year 4: 135 118
Year 5: 118 103
Year 6: 103 90
Year 7: 90 79
Actual Output:
Year 1: 200 199
Year 2: 199 198
Year 3: 198 197
Year 4: 197 196
Year 5: 196 195
Year 6: 195 194
Year 7: 194 193
I built the program according to the following assignment:
In a population, the birth rate is the percentage increase of the population due to births, and the death rate is the percentage decrease of the population due to deaths. Write a program that asks for the following:
The starting size of a population (minimum 2) (Prompt Enter starting size:)
The annual birth rate (Prompt Enter annual birth rate:)
The annual death rate (Prompt Enter annual death rate:)
The number of years to display (minimum 1) (Prompt Enter years to display:)
The program should then display the starting population and the projected population at the end of each year. It should use a function that calculates and returns the projected new size of the population after a year. The formula is
N = P(1 + B)(1 - D)
where N is the new population size, P is the previous population size, B is the birth rate, and D is the death rate. Annual birth rate and death rate are the typical number of births and deaths in a year per 1000 people, expressed as a decimal. So, for example, if there are normally about 32 births and 26 deaths per 1000 people in a given population, the birth rate would be .032 and the death rate would be .026.
My code:
#include <iostream>
using namespace std;
int projectedNewSize(float population, float annualBirthRate, float annualDeathRate) {
float annualBirthRate2 = annualBirthRate / 1000;
float annualDeathRate2 = annualDeathRate / 1000;
int newpopulation = population * (1 + annualBirthRate2) * (1 - annualDeathRate2);
return newpopulation;
}
int main() {
int populationStartingSize = 0;
float annualBirthRate = 0;
float annualDeathRate = 0;
int numberOfYearsToDisplay = 0;
do {
cout << "Enter starting population size: ";
cin >> populationStartingSize;
cout << "Enter annual birth rate: ";
cin >> annualBirthRate;
cout << "Enter annual death rate: ";
cin >> annualDeathRate;
cout << "Enter years to display: ";
cin >> numberOfYearsToDisplay;
} while (!(populationStartingSize >= 2) || !(numberOfYearsToDisplay >= 1));
int population;
for (int i = 1; i <= numberOfYearsToDisplay; i++) {
cout << "Year " << i << ": " << populationStartingSize << " ";
population = projectedNewSize(populationStartingSize, annualBirthRate, annualDeathRate);
cout << population << endl;
populationStartingSize = population;
}
system("pause");
return 0;
}
So, The answer is
There is no need to divide the annualBirthRate and the annualDeathRate by 1000. Since annualBirthRate is calculated as annual births per 1000 of a population, It need not be divided by 1000 again.
Thus removing these lines
float annualBirthRate2 = annualBirthRate / 1000;
float annualDeathRate2 = annualDeathRate / 1000;
and changing
int newpopulation = population * (1 + annualBirthRate2) * (1 - annualDeathRate2);
to
int newpopulation = population * (1 + annualBirthRate) * (1 - annualDeathRate);
So, the final code would look like this:
#include <iostream>
using namespace std;
int projectedNewSize(float population, float annualBirthRate, float annualDeathRate) {
int newpopulation = population * (1 + annualBirthRate) * (1 - annualDeathRate);
return newpopulation;
}
int main() {
int populationStartingSize = 0;
float annualBirthRate = 0;
float annualDeathRate = 0;
int numberOfYearsToDisplay = 0;
do {
cout << "Enter starting population size: ";
cin >> populationStartingSize;
cout << "Enter annual birth rate: ";
cin >> annualBirthRate;
cout << "Enter annual death rate: ";
cin >> annualDeathRate;
cout << "Enter years to display: ";
cin >> numberOfYearsToDisplay;
} while (!(populationStartingSize >= 2) || !(numberOfYearsToDisplay >= 1));
int population;
for (int i = 1; i <= numberOfYearsToDisplay; i++) {
cout << "Year " << i << ": " << populationStartingSize << " ";
population = projectedNewSize(populationStartingSize, annualBirthRate, annualDeathRate);
cout << population << endl;
populationStartingSize = population;
}
system("pause");
return 0;
}
You guys discussed in the comments section and left the question unanswered..
int projectedNewSize(float population, float annualBirthRate, float annualDeathRate) {
int newpopulation = roundf(population * (1.0 + annualBirthRate) * (1.0 - annualDeathRate);
return newpopulation;
}
In the calculatiton you dont have to consider the factor of 1000 if it is already done in the input values. But if you want a 'most accurate' table you have to round the values in a proper mind. The return of the calculation is a float. If you assign it to an int - it always will be truncated. A little difference wich will be carried over from one loop to the next, ending up in some reasonable differences to the expected values at the end. The most proper way would be to change the type of 'newcalculation' to float and round only when display the value.
N = P + BP - DP
Program asked for birthrate and death rate, assume user entered 5 for 5%.
Basic math needs to be calculated here 5/100 = 0.05
The formula is now
N = P + (BP/100) - (DP/100)
Replace
float annualBirthRate2 = annualBirthRate / 1000;
float annualDeathRate2 = annualDeathRate / 1000;
int newpopulation = population * (1 + annualBirthRate2) * (1 - annualDeathRate2);
With
int newpopulation = population + (population * birthRate/100) - (population * deathRate/100)