Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Scrivere un programma che legge da std input una sequenza di voti (in trentesimi),
- ciascuno con i propri CFU, e quindi calcola e stampa la media pesata rispetto ai CFU.
- Il programma accetta soltanto voti compresi tra 18 e 30.
- L'immissione termina quando si inserisce un voto negativo.
- n.b. si ricorda che la media pesata si calcola dividendo la somma dei numeri
- ottenuti dalla moltiplicazione di ciascun voto per i suoi CFU con la somma di tutti i CFU;
- ad es., (27*6 + 22*12 + 18*9) / (6+12+9) = 21.7777).
- */
- #include <iostream>
- using namespace std;
- int main()
- {
- // exam grade, given by user as input. Must be initialized for while condition but initialization value is irrelevant
- int grade = 99;
- int credits; // exam credits, given by user as input
- int n = 0; // number of grades given as (valid) input
- int weightedGradesSum = 0; // sum of (exam grade * exam credits) values
- int creditsSum = 0; // sum of total exam credits
- while (grade > 0)
- {
- cout << "Immettere un voto (negativo per smettere): ";
- cin >> grade; // overwrite grade with user input
- if (grade < 0) // user did not provide a negative grade value as input
- {
- cout << "Hai immesso " << n << " voti." << endl;
- // Don't print average if there are no valid input votes.
- // Cast sum to float to have / operator return a float as its result
- if (n > 0) cout << "La media pesata dei tuoi voti è: " << (float)weightedGradesSum / creditsSum;
- // Exit program since user provided a negative input
- return 0;
- }
- // Does nothing, goes to next iteration of cycle
- else if (grade < 18 || grade > 30) cout << "Il voto deve essere compreso tra 18 e 30" << endl;
- // Only take credits value if user provided a valid grade as input
- else
- {
- cout << "Immettere i CFU del corso: ";
- cin >> credits; // overwrite exam credits value with user input
- creditsSum = creditsSum + credits; // update sum of exam credits
- weightedGradesSum = weightedGradesSum + grade * credits; // update sum of (exam grade * exam credits) values
- n = n + 1; // update counter of received valid exam grades
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement