Practise--《C++ primer plus》习题程序编写
《C++ primer plus》第七章8、9题,编程格式思路纯属个人喜好:
8.
#include <iostream> using namespace std; const int SLEN = 30; struct student { char fullname[SLEN]; char hobby[SLEN]; int opplevel; }; int getinfo ( student pa[ ], int n ); void display1 ( student st ); void display2 ( const student * ps ); void display3 ( const student pa[ ], int n ); int main() { cout << "Enter class size: "; int class_size; cin >> class_size; while ( cin.get() != '\n' ) continue; student * ptr_stu = new student[class_size]; int entered = getinfo ( ptr_stu, class_size ); for ( int i = 0; i < entered; i++ ) { display1(ptr_stu[i]); display2(&ptr_stu[i]); } display3(ptr_stu,entered); delete [] ptr_stu; cout << "Done\n"; return 0; } int getinfo( student pa[], int n ) { int count = 0; for (int i = 0; i < n; i++) { cout << "Please input student's name: "; cin.getline( pa[i].fullname, SLEN ); if ( strlen(pa[i].fullname) != 0 ) //判断是否为空行 { count += 1; cout << "Please input student's hobby: "; cin.getline( pa[i].hobby, SLEN ); cout << "Please input student's ooplevel: "; cin >> pa[i].opplevel; while ( cin.get() != '\n' ) continue; } else break; } cout << "In fact we have " << count << " students.\n" << endl; return count; } void display1( student st ) { cout << st.fullname << '\t' << st.hobby << '\t' << st.opplevel <<endl; } void display2( const student * ps ) { cout << ps->fullname << '\t' << ps->hobby << '\t' << ps->opplevel << endl; } void display3( const student pa[ ], int n ) { for (int i = 0; i < n; i++ ) { cout << pa[i].fullname << '\t' << pa[i].hobby << '\t' << pa[i].opplevel << endl; } }
9.
(1) 这里是让用户输入两个数计算或者按q退出:
#include <iostream> using namespace std; double add( double x, double y ) { return x + y; } double calculate ( double x, double y, double (*f)( double , double ) ) { return f( x, y ); } int main( ) { double x, y; cout << "Please input two numbers or end by q: "; while( (cin >> x >> y ) ) {double result = calculate ( x, y, add ); cout << "Result is " << result << endl; cout << "Please input two numbers or end by q: "; } return 0; }
(2) 用了一个指向函数的指针数组:
#include <iostream> using namespace std; double add( double x, double y ) { return x + y; } double mlu( double x, double y ) { return x * y; } double calculate ( double x, double y, double (*f)( double , double ) ) { return f( x, y ); } int main( ) { double x, y; double (*pf[2]) ( double, double ) = {add, mlu}; char * cp[2] = {"add", "mlu"}; cout << "Please input two numbers or end by q: "; while( (cin >> x >> y ) ) { for (int i = 0; i < 2; i++ ) cout << cp[i] << " = " << calculate( x, y, pf[i] ) << endl; cout << "Please input two numbers or end by q: "; } return 0; }