c++ - Chapter 4 Stroustrup Drill. A challenging step (at least for me!) -


i'm working through stroustrups's "programming principles , practice using c++" , got stuck in 1 exercise.

here indications :

1) write program consists of while-loop (each time around loop) reads in 2 ints , prints them. exit program when terminating '|' entered.  2)change program write out smaller value is: followed smaller of numbers , larger value is: followed larger value.  3)augment program writes line numbers equal (only) if equal.  4)change program uses doubles instead of ints.  5)change program writes out numbers equal after writing out larger , smaller if 2 numbers differ less 1.0/100.  6) change body of loop reads 1 double each time around. define 2 variables keep track of smallest , largest value have seen far. each time through loop write out value entered. if it’s smallest far, write smallest far after number. if largest far, write largest far after number. 

this code have far:

    int main(){      double number1 = 0;     double number2 = 0;     double maximum = 0;     double minimum = 0;       cout << " keep entering numbers. if want exit program press alt + z" << endl;     while (cin >> number1 && cin >> number2) {  if (number1 == '@' || number2 == '@')    {     break;     }  else if (number1 < number2){     cout << "the smaller value " << number1 << '.' << endl;     cout << "the larger value " << number2 << '.' << endl;     maximum = number2;     minimum = number1;     if  (number2 - number1 < 0.01) {         cout << "the numbers equal";      } }  else if ( number1 > number2) {     cout << "the smaller value " << number2 << '.' << endl;     cout << "the larger value " << number1 << '.' << endl;     maximum = number1;     minimum = number2;         if  (number1 - number2 < 0.01) {         cout << "the numbers equal";     }  }  else {     cout << "both numbers same." << endl; }     } 

can me modify find largest, smallest number? i've read , found sorted vector solution can't seem apply problem.

much appreciated :)

if want keep running count of maximum , minimum , not make structural changes existing program,

you'll need '#include < algorithm >' unless want roll own min , max functions.

instead of:

maximum = number1; minimum = number2; 

use this:

maximum = (maximum < max(number1, number2)) ? max(number1, number2) : maximum; minimum = (minimum > min(number1, number2)) ? min(number1, number2) : minimum; 

Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -