Advertisement
Guest User

Untitled

a guest
Oct 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.33 KB | None | 0 0
  1. /*
  2.     Scrivere un programma che legge da std input una sequenza di voti (in trentesimi),
  3.     ciascuno con i propri CFU, e quindi calcola e stampa la media pesata rispetto ai CFU.
  4.  
  5.     Il programma accetta soltanto voti compresi tra 18 e 30.
  6.     L'immissione termina quando si inserisce un voto negativo.
  7.    
  8.     n.b. si ricorda che la media pesata si calcola dividendo la somma dei numeri
  9.     ottenuti dalla moltiplicazione di ciascun voto per i suoi CFU con la somma di tutti i CFU;
  10.     ad es., (27*6 + 22*12 + 18*9) / (6+12+9) = 21.7777).
  11. */
  12.  
  13. #include <iostream>
  14.  
  15. using namespace std;
  16.  
  17.  
  18. int main()
  19. {
  20.     // exam grade, given by user as input. Must be initialized for while condition but initialization value is irrelevant
  21.     int grade = 99;
  22.  
  23.     int credits; // exam credits, given by user as input
  24.     int n = 0; // number of grades given as (valid) input
  25.     int weightedGradesSum = 0; // sum of (exam grade * exam credits) values
  26.     int creditsSum = 0; // sum of total exam credits
  27.  
  28.     while (grade > 0)
  29.     {
  30.         cout << "Immettere un voto (negativo per smettere): ";
  31.         cin >> grade; // overwrite grade with user input
  32.  
  33.         if (grade < 0) // user did not provide a negative grade value as input
  34.         {
  35.             cout << "Hai immesso " << n << " voti." << endl;
  36.  
  37.             // Don't print average if there are no valid input votes.
  38.             // Cast sum to float to have / operator return a float as its result
  39.             if (n > 0) cout << "La media pesata dei tuoi voti è: " << (float)weightedGradesSum / creditsSum;
  40.  
  41.             // Exit program since user provided a negative input
  42.             return 0;
  43.         }
  44.  
  45.         // Does nothing, goes to next iteration of cycle
  46.         else if (grade < 18 || grade > 30) cout << "Il voto deve essere compreso tra 18 e 30" << endl;
  47.  
  48.         // Only take credits value if user provided a valid grade as input
  49.         else
  50.         {
  51.             cout << "Immettere i CFU del corso: ";
  52.             cin >> credits; // overwrite exam credits value with user input
  53.             creditsSum = creditsSum + credits; // update sum of exam credits
  54.             weightedGradesSum = weightedGradesSum + grade * credits; // update sum of (exam grade * exam credits) values
  55.             n = n + 1; // update counter of received valid exam grades
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement