1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#include <iostream>
#include <iomanip>
int get_number( int min_value, int max_value ) ;
void print_powers_in_range( int number_from, int number_to, int width ) ;
int main() {
const int min_start = 1 ;
const int max_start = 50 ;
const int max_end = 100 ;
const int width = 10 ;
std::cout << "starting value [" << min_start << "..." << max_start << "]? " ;
const int start_value = get_number( min_start, max_start ) ;
std::cout << "ending value [" << start_value << "..." << max_end << "]? " ;
const int end_value = get_number( start_value, max_end ) ;
print_powers_in_range( start_value, end_value, width ) ;
}
int get_number( int min_value, int max_value ) {
int number ;
if( std::cin >> number && number >= min_value && number <= max_value ) return number ;
std::cout << "enter a number in [" << min_value << "..." << max_value << "]: " ;
// you may want to ignore these two lines for now
std::cin.clear() ; // clear a possible failed state (for eg. if letters were entered instead of digits)
std::cin.ignore( 1000, '\n' ) ; // throw the bad input away
return get_number( min_value, max_value ) ; // try again (repeat the same function)
}
void print_powers( int number, int width ) {
const int nsquared = number * number ;
const int ncubed = nsquared * number ;
std::cout << std::setw(width) << number << std::setw(width) << nsquared << std::setw(width) << ncubed << '\n' ;
}
void print_powers_in_range( int number_from, int number_to, int width ) {
std::cout << std::setw(width) << "Number" << std::setw(width) << "Squared" << std::setw(width) << "Cubed\n" ;
for( int number = number_from ; number <= number_to ; ++number ) print_powers( number, width ) ;
}
|