Г. Шилтд - Самоучитель C++ (PDF) (1114887), страница 81
Текст из файла (страница 81)
show{) ;return 0;6. Пропущены слова "общего" и "специальным".Упражнения8.2"1. Hnclude <iostream>using namespace std;'int main()<cout .setf (ios: : showpos) ;cout « -10 « ' ' « 10 « r\n';return 0;}2. ^include <iostream>using namespace std;int main{){cout. setf {ios: : showpoint | ios: : uppercase [ ios: : scientific) ;cout « 100.0;приложение В. Ответы на вопросы и решения упражненийreturn 0;3. ^include <iostream>using namespace std;int main(){ios::fmtflags f;f = cout.flags(); // сохранение флаговcout.unsetf(ios::dec);cout,setf(ios::showbase | ios::hex);cout « 100 « '\n';cout-flags(f); // возврат флагов в исходное состояниеreturn 0;8.31. /* Создание таблицы натуральных и десятичных логарифмов чиселот 2 до 100*/tfinclude <iostream>^include <cmath>using namespace std;int main ()double x;cout,precision(5) ;cout « "xIg xIn x\n\n";for(x = 2.0; x <= 100.0; x++) {cout.width(10);cout « x « " ";cout.widthUO)/cout « loglOCx) « " ";cout.width(10);cout « log(x) « "\n";return 0;}579580Сзмоучитель^:++2.
^include <iostream>ttinclude <cstring>using namespace std;void center(char *s);int mainf)center("Это здесь!");.center("Мне нравится C++.");return 0;void center(char *s){int len;len = 40 + ( s t r l e n ( s } / 2 ) ;cout.width(len);cout « з « "\n";8.4la.// Таблица натуральных и десятичных логарифмов чисел от 2 до 100^include <iostream>^include <iomanip>ftinclude <cmath>using namespace std;int main()double x;cout « setprecision(S);cout « "xIg xIn x\n\n";for(x = 2.0; x <= 100.0; x++} {cout « setw(10} « x « " ";cout « setw(lO) « loglO(x) « " ";cout « setw(10} « log(x) « "\n";return 0;lb.^include <iostream>^include <iomanip>Приложение В.
Ответы на вопросы и решения упражнений581^include <cstring>using namespace std;void center(char *s);inttmain()center("Это з д е с ь ! " ) ;centsг("Мне нравится C++.");return 0;void centerfchar *s)int len;len = 40 + (strlen(s)/2);cout « setw(len) « s « "\n";}2. cout « setiosflags(ios:ishowbase I ios::hex) « 100;3. Установка флага boolalpha для потока вывода приводит к тому, что значениябулева типа выводятся на экран в виде слова trae или false. Установка флагаboolalpha для потока ввода позволяет вводить значения булева типа с помощью слова trae или false.8.51. ^include <iostream>#include <cstring>#include <cstdlib>using namespace std;class strtype {char *p;intlen;public:strtype(char *ptr);-strtype() (delete [] p; }friend ostream soperator«(ostream &stream, strtype &ob);strtype::strtype(char *ptr)len = strlen(ptr) + 1;582_____Самоучительр = new char [len];if(!p> (cout « "Ошибка выделения памятиХп";exit(l);}strcpy(p, ptr} ;ostream &operator« {ostream &stream, strtype &ob){stream « ob.p;return stream;int main(){strtype si ("Это проверка"), з2("Мне нравится C++"};cout « si;cout « endl « s2 « endl;return 0;2.
Hnclude <iostream>using namespace std;class planet {protected:double distance; // расстояние в милях от Солнцаint revolve;// полный оборот в дняхpublic :planet {double d, int r) { distance = d; revolve = r; )class earth: public planet {double circumference; // окружность орбитыpublic:earth(double d, int r) : planetfd, r) (circumference = 2 * distance * 3.1416;1friend ostream &operator« (ostream sstream, earth sob) ;};ostream &operator« (ostream ^stream, earth Sob){stream « "Расстояние от Солнца: " « ob.
distance « '\n';C++ПриложениеВ,Ответынавопросыирешенияупражнений_533stream « "Оборот вокруг Солнца: " « ob. revolve « ' \ п ' ;stream « "Окружность орбиты: " « ob. circumference;stream « ' \n' ;return stream;int main()(earth ob(93000000,365);cout « ob;return 0;3. Пользовательская функция вывода не может быть функцией- членом потому,что объект, который вызывает функцию, не является объектом определенного пользователем класса.8.61. tfinclude <iostream>ttinclude <cstring>^include <cstdlib>using namespace std;class strtype {char *p;int len;public:strtype(char *ptr);-strtype 0 { delete [] p; }friend ostream &operator« [ostream sstream, strtype &ob)friend istream soperator»(istream fistream, strtype &ob)};strtype::strtype(char *ptr){len = strlen(ptr)+l;p = new char [len];if(!p) {cout « "Ошибка выделения памяти\п";exit(1);strcpy(p, ptr);584Самоучитель C++ostream &operator« (ostream sstream, strtype sob)stream « ob.p;return stream;istream ^operator» (istream sstream, strtype sob){char temp[255J;stream » temp;if(strlen(temp) >= ob.len) {delete И ob.p;ob.len = strlen(temp) + 1;ob.p = new char [ob.len];if(!ob.p) {cout « "Ошибка выделения памяти\п";exit(1);}1strcpy(ob.p, temp);return stream;}int main ()fstrtype si("Это проверка"), з2("Мне нравится C++")cout « si;cout « '\n' « s2;cout « "ХпВведите строку: ";cin » si;cout « si;return 0;2.
^include <iostream>using namespace std;class factor jint num;// числоint Ifact; // наименьший делительpublic:factor (int i);Приложение В. Ответы на вопросы и решения упражненийfriend ostream &operator« (ostream ustream, factor ob) ;friend istream ^operator» (istream ustream, factor &ob) ;factor: : factor (int i){int n;nura = i;for(n=2;if {! (i%n) } break;if (n«i/2) ) Ifact = n;else Ifact = 1;}istream ^operator» (istream sstream, factor Sob){stream » ob.num;int n;for{n=2; n<(ob.num/2) ; n+4}if ( ! (ob.nurnfcn) ) break;if (n<(ob.num/2) ) ob. Ifact = n;else ob. Ifact = 1;return stream;Iostream fioperator« (ostream Sstream, factor ob}{stream « ob. Ifact « " Это наименьший делитель числа "stream « ob.num « '\n';return stream;}int main ( ){factor o(32) ;cout « o;cin » o;cout « o;return 0;555586Самоучитель C++Проверка усвоения материала главы 81. tinclude <iostraam>using namespace std;int main(){cout « 100 « ' ' ;cout.unsetf (ios: :dec) ; // сброс флага deccout.setf {ios: :hex) ;cout « 100 « ' ' ;cout ,unsetf( ios: : hex) ; // сброс флага hexcout.setf (ios: :oct) ;cout « 100 « '\n';return 0;2.
^include <iostream>using namespace std;int main ( )I"cout.setf (ios: :left) ;cout.precision(2) ;cout. fill ('*'}, •cout.width(20) ;cout « 1000.5354 « '\nr;return 0;За. #include <iostream>using namespace std;int main(){cout « 100 « ' ';cout « hex « 100 « ' ';cout « oct « 100 « '\n';return 0;ПриложениеВ.Ответынавопросыирешенияупражнений3b. #include <iostream>^include <iomanip>using namespace std;int main()(cout «cout «cout «cout «setiosflags (ios: :left) ;setprecision (2) ;setfilK1*1} ;setw(20) ;cout « 1000.5354 « '\n';return 0;4. ios: : fmtf lags f;f = cout. flags (); // сохранениеcout. flags ( ) ; // отображение5.us?ttinc"->stream>. HU!: • "-ас std;L t exponent;double result;public:pwr(int b, intfriend ostreamfriend istream};// результат возведения в степеньe);&operator«(ostream sstream, pwr ob);fioperator» (istream fistream, pwr &ob)pwr::pwr(int b, int e){base = b;exponent = e;result = 1;for{; e; e —) result = result * base;}ostream &operator«(ostream Sstream, pwr ob)!stream « ob.base « " в степени " « ob.exponent;stream « " равно " « ob.result « '\n';_587Самоучитель C++588return stream;»istream ^operator» (istream sstrearn, pwr sob)(int b, e;'cout « "Введите основание и показатель степени:stream » fa » e;-.pwr temp(b, e) ;ob = temp;return stream;}int main ( )<pwr ob(10, 2) ;cout « ob;cin » ob;cout « ob;return 0;,6.
// Эта программа рисует квадраты#include <iostream>using namespace std;class box {int len;public:box(int 1) { len - 1; }friend ostream &operator« (ostream ^stream, box ob) ;// рисование квадратаostream &operator« (ostream &stream, box ob)int i, j;for{i=0; i<ob.len; i++) stream « '*';stream « '\n';for(i=0; i<ob.len-2; i++) {stream « '* ' ;for(j=0; j<ob.len-2; j++) stream « ' ';Приложение В. Ответы на вопросы и решения упражненийstream « "*\п";1for{i=0; i<ob.len; i++) stream « '*';stream « ' \n';return stream;}int main(){box Ы{4), Ь2(7) ;cout « Ы « endl « b2;return 0;Проверка усвоения материала в целом1.
^include <iostream>using namespace std;^define SIZE 10// Объявление класса stack для символовclass stack {char stck[SIZE]; // содержит стекint tos; // индекс вершины стекаpublic:stack () ;void push (char ch) ; // помещает в стек символchar pop(); // выталкивает из стека символfriend ostream &operator« (ostream sstream, stack ob) ;};// Инициализация стекаstack: : stack (){tos=0;// Помещение символа в стекvoid stack: :push(char ch){if (tos==SIZE) (cout « "Стек полон";return;589590___Самоучительstck[tos]=ch/tos-н-;}// Выталкивание символа из стекаchar stack:: pop (){if (tos==0) {cout « "Стек пуст";return 0; // возврат нуля при пустом стеке}tOS--;return stck[tos];}ostream &operator« (ostream Sstream, stack ob){char ch;while (ch=ob.pop() } stream « ch;stream « endl;return stream;int main (){stack s;s.pushf 'a') ;s . push ( ' b ' ) ;s.push ( 'c' ) ;cout « s;cout « s;return 0;2.
^include <iostream>^include <ctime>using namespace std;class watch {time_t t;public:watch {} ( t = time (NULL); }friend ostream &operator« {ostream Sstream, watch ob) ;C++Приложение В, Ответы на вопросы и решения упражненийostream &operator« (ostream &stream, watch ob){struct tin *localt;localt - localtime(sob.t);stream « asctime(localt) « endl;return stream;}int main ()twatch w;cout « w;return 0;3.
#include <iostream>using namespace std;class ft_to_inches {double feet;double inches;public:void set (double f} {feet = f;inches = f * 12;}friend istream soperator» (istrearn sstrearn, ft_to_inches Sob);friend ostream &operator«(ostream fistream, ft_to_inches ob);};istream separator»{istream fistream, ft_to_inches iob)1double f;cout « "Введите число футов: ";stream » f;ob.set(f);return stream;1ostream &operator« (ostream Sstrearn, ft_to_inches ob)tstream « ob.feet « " футов равно " « ob.inches;stream « " дюймам\п";597Самоучитель C++592return stream;int main{)ft_to__inches x;cin » x;cout « x;return 0;ГЛАВА 9Повторение пройденного1. ^include <iostream>using namespace std;int main (){cout.width(40);cout. fillC : ') ;cout « "C++ прекрасен" « '\n';return 0;2.
#iriclude <iostream>using namespace std;int main(){cout.precision(4};cout « 10.0/3.0 « '\np;return 0;I3. #include <iostream>^include <iomanip>using namespace std;int main(){cout « setprecision(4) « 10.0/3.0 « '\n';ПриложениеВ.Ответынавопросыирешенияупражнений_593return 0;4. Пользовательская функция вывода — это перегруженная оператор-функцияoperator«(), которая передает данные класса в поток вывода.