Note04

书:C++大学教程(第七版)
1. cmath头文件提供了能够进行通用数学计算的函数集合。
这里写图片描述
2. 数据类型
这里写图片描述
3. 标准库头文件
这里写图片描述
这里写图片描述
这里写图片描述
4. rand函数的原型在中
5. srand()和rand()
srand()就是给rand()提供种子seed,通常将时间作为种子;
srand(time(0));
如果srand每次输入的数值是一样的,那么每次运行产生的随机数也是一样的

srand( (unsigned)time( NULL ) ); 
/* Display 10 numbers. */ 
for( i = 0; i < 10;i++ ) 
    printf( " %6d/n", rand() ); 
}
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
    srand(time(0));
    for (size_t i = 0; i < 100; i++)
    {
        if (i > 0 && i % 5 == 0)
        {
            cout << endl;
        }
        cout << rand()<<"\t";
    }
    system("pause");
    return 0;
}
  1. 递归和迭代
    迭代使用循环结构,递归使用选择结构;迭代显示地使用循环结构,递归通过重复的函数调用实现循环;
  2. 将指针传递给函数的4种方式:
    (1)指向非常量数据的非常量指针:具有最大的访问权限,如:int *countPtr;
    (2)指向常量数据的非常量指针:可以被修改以指向任何适当类型的其他数据项,但是不能通过该指针来修改它所指向的数据。可以用这种指针为函数接收数组实参,函数处理数组的每个元素,但不允许修改数据。形如:const int *countPtr;从右到左读作“countPtr是指向一个字符常量的指针”
    (3)指向非常量数据的常量指针:始终指向同一个内存位置,通过该指针可以修改这个位置上的数据。这就是数组名的默认情况,数组名是指向这个数组开始处的常量指针。使用数组名和数组下标,可以访问和修改数组中的所有元素。可以用来接收数组作为函数的实参,在函数中用数组下标表示法访问数组元素。声明为const的指针在声明时必须被初始化,如果指针是函数参数,他被传递给函数的指针初始化。形如:int * const ptr = &x;
    (4)指向常量数据的常量指针:具有最小的访问权限。这种指针总是指向内存中相同的位置,并且不能用该指针修改这个内存位置的数据。如果函数接收一个数组做参数,只是用数组下标表示法读取数组而不修改数组,那么应该用这种指针。形如:const int * const ptr = &x;从右大左读作“ptrr是指向一个整数常量的常量指针”。当试图修改ptr指向的数据和存储在该指针变量中的地址时,产生错误信息。注意:当程序试图间接引用ptr,或当程序试图输出ptr所指向的值时,不会发生错误。
  3. 数组名是常量指针,总是指向数组的开头。如:b += 3;将引起错误;
int b[5];
int *bPtr;
bPtr = b;//等价于bPtr = &b[0];

第三个元素的值: *(b+2)
9. 函数指针

bool (* compare ) (int , int )
关键字bool表示所指向的函数返回一个bool值。文本(*compare)表示函数指针的名字(此处的*表明参数compare是一个指针)。文本(int,int)表示compare所指向的函数有两个整型参数。*compare的两边要加上圆括号,才能表示compare是一个函数指针。如果不加圆括号,该声明将变成下述形式:
bool * compare(int, int )
那么它表示一个接受两个整数做参数、并返回一个指向bool值的指针的函数。
(*compare)( work[ smallestOrLargest ], work[ index ] )
就想简介引用变量指针可以访问变量值一样,简介引用函数指针可以执行该函数。*compare两边的圆括号是必须的,如果没有,*运算符试图间接引用函数调用所返回的值。不间接引用函数指针,也可以调用该函数,如下所示:
compare( work[ smallestOrLargest ], work[ index ] )
这里将指针直接作为函数名使用。提倡通过指针调用函数的第一种方法,因为他显示地说明compare是一个函数指针,通过间接引用这个指针来调用函数。通过指针调用函数的第二种犯法使compare看起来好像是程序中的一个实际函数的名字。这会使程序的用户感到迷惑,他想看函数compare的定义,但却发现在文件中它并没有被定义。
// Multipurpose sorting program using function pointers.
#include <iostream>
#include <iomanip>
using namespace std;
// prototypes
void selectionSort( int [], const int, bool (*)( int, int ) );
void swap( int * const, int * const );   
bool ascending( int, int ); // implements ascending order
bool descending( int, int ); // implements descending order
int main()
{
   const int arraySize = 10;
   int order; // 1 = ascending, 2 = descending
   int counter; // array index
   int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
   cout << "Enter 1 to sort in ascending order,\n" 
      << "Enter 2 to sort in descending order: ";
   cin >> order;
   cout << "\nData items in original order\n";

   // output original array
   for ( counter = 0; counter < arraySize; counter++ )
      cout << setw( 4 ) << a[ counter ];
   // sort array in ascending order; pass function ascending 
   // as an argument to specify ascending sorting order
   if ( order == 1 ) 
   {
      selectionSort( a, arraySize, ascending );
      cout << "\nData items in ascending order\n";
   } // end if
   // sort array in descending order; pass function descending
   // as an argument to specify descending sorting order
   else 
   {
      selectionSort( a, arraySize, descending );
      cout << "\nData items in descending order\n";
   } // end else part of if...else
   // output sorted array
   for ( counter = 0; counter < arraySize; counter++ )
      cout << setw( 4 ) << a[ counter ];
   cout << endl;
} // end main
// multipurpose selection sort; the parameter compare is a pointer to
// the comparison function that determines the sorting order
void selectionSort( int work[], const int size,
                    bool (*compare)( int, int ) )
{
   int smallestOrLargest; // index of smallest (or largest) element
   // loop over size - 1 elements
   for ( int i = 0; i < size - 1; i++ )
   {
      smallestOrLargest = i; // first index of remaining vector
      // loop to find index of smallest (or largest) element
      for ( int index = i + 1; index < size; index++ )
         if ( !(*compare)( work[ smallestOrLargest ], work[ index ] ) )
            smallestOrLargest = index;
      swap( &work[ smallestOrLargest ], &work[ i ] );
   } // end if
} // end function selectionSort
// swap values at memory locations to which 
// element1Ptr and element2Ptr point
void swap( int * const element1Ptr, int * const element2Ptr )
{
   int hold = *element1Ptr;
   *element1Ptr = *element2Ptr;
   *element2Ptr = hold;
} // end function swap
// determine whether element a is less than 
// element b for an ascending order sort
bool ascending( int a, int b )
{
   return a < b; // returns true if a is less than b
} // end function ascending
// determine whether element a is greater than 
// element b for a descending order sort
bool descending( int a, int b )
{
   return a > b; // returns true if a is greater than b
} // end function descending
  1. const
    (1) 对于const对象,不允许进行成员函数的调用,除非成员函数本身也声明为const。这一点非常严格,即使是不修改对象的获取对象函数也不行。
    (2)不为const数据成员提供相应地成员初始化器是一个编译错误。
  2. Friend
    (1) 类的friend函数(友元函数)在类的作用域之外定义,却具有访问类的非public(以及public)成员的权限。单独的函数或整个类都已被声明为另一个类的友元。
    (2) 使用friend函数可以提高程序的性能。
    (3) 友元声明可以出现在类的任何地方。
  3. 多种格式输出日期
    格式:
    DDD YYYY
    MM/DD/YYYY
    June 14, 1992
    Date.h
#ifndef DATE_H
#define DATE_H
#include <string>
using namespace std;
class Date 
{
public:
   Date(); // default constructor uses <ctime> functions to set date
   Date( int, int ); // constructor using ddd yyyy format
   Date( int, int, int ); // constructor using dd/mm/yy format
   Date( string, int, int ); // constructor using Month dd, yyyy format
   void setDay( int ); // set the day
   void setMonth( int ); // set the month
   void print() const; // print date in month/day/year format
   void printDDDYYYY() const; // print date in ddd yyyy format
   void printMMDDYY() const; // print date in mm/dd/yy format
   void printMonthDDYYYY() const; // print date in Month dd, yyyy format
   ~Date(); // provided to confirm destruction order
private:
   int month; // 1-12 (January-December)
   int day; // 1-31 based on month
   int year; // any year
   // utility functions 
   int checkDay( int ) const; // check if day is proper for month and year 
   int daysInMonth( int ) const; // returns number of days in given month
   bool isLeapYear() const; // indicates whether date is in a leap year
   int convertDDToDDD() const; // get 3-digit day based on month and day
   void setMMDDFromDDD( int ); // set month and day based on 3-digit day
   string convertMMToMonth( int ) const; // convert mm to month name
   void setMMFromMonth( string ); // convert month name to mm 
   int convertYYYYToYY() const; // get 2-digit year based on 4-digit year
   void setYYYYFromYY( int ); // set year based on 2-digit year
}; // end class Date
#endif
Date.cpp
#include <iostream>
#include <iomanip>
#include <ctime>
#include "Date.h" // include Date class definition
using namespace std;
// default constructor that sets date using <ctime> functions
Date::Date()
{
   // pointer of type struct tm which holds calendar time components
   struct tm *ptr; 
   time_t t = time( 0 ); // determine current calendar time      

   // convert current calendar time pointed to by t into
   // broken down time and assign it to ptr
   ptr = localtime( &t ); 

   day = ptr->tm_mday; // broken down day of month
   month = 1 + ptr->tm_mon; // broken down month since January
   year = ptr->tm_year + 1900; // broken down year since 1900
} // end Date constructor
// constructor that takes date in ddd yyyy format
Date::Date( int ddd, int yyyy )
{
   year = yyyy; // could validate
   setMMDDFromDDD( ddd ); // set month and day based on ddd
} // end Date constructor
// constructor that takes date in mm/dd/yy format
Date::Date( int mm, int dd, int yy )
{
   setYYYYFromYY( yy ); // set 4-digit year based on yy
   setMonth( mm ); // validate and set the month
   setDay( dd ); // validate and set the day
} // end Date constructor
// constructor that takes date in Month dd, yyyy format
Date::Date( string monthName, int dd, int yyyy )
{ 
   setMMFromMonth( monthName ); // set month based on month name
   setDay( dd ); // validate and set the day
   year = yyyy; // could validate
} // end Date constructor
// validate and store the day
void Date::setDay( int d )
{
   day = checkDay( d ); // validate the day
} // end function setDay
// validate and store the month
void Date::setMonth( int m )
{
   if ( m > 0 && m <= 12 ) // validate the month
      month = m;
   else 
   {                     
      month = 1; // invalid month set to 1
      cout << "Invalid month (" << m << ") set to 1.\n";
   } // end else
} // end function setMonth
// print Date object in form: month/day/year
void Date::print() const
{
   cout << month << '/' << day << '/' << year << endl; 
} // end function print
// print Date object in form: ddd yyyy
void Date::printDDDYYYY() const
{
   cout << convertDDToDDD() << ' ' << year << endl;
} // end function printDDDYYYY
// print Date object in form: mm/dd/yy
void Date::printMMDDYY() const
{
   cout << setw( 2 ) << setfill( '0' ) << month << '/' 
      << setw( 2 ) << setfill( '0' ) << day << '/' 
      << setw( 2 ) << setfill( '0' ) << convertYYYYToYY() << endl;
} // end function printMMDDYY
// print Date object in form: Month dd, yyyy
void Date::printMonthDDYYYY() const
{
   cout << convertMMToMonth( month ) << ' ' << day << ", " << year 
      << endl;
} // end function printMonthDDYYYY
// output Date object to show when its destructor is called
Date::~Date()
{ 
   cout << "Date object destructor for date ";
   print();
   cout << endl;
} // end ~Date destructor
// utility function to confirm proper day value based on 
// month and year; handles leap years, too
int Date::checkDay( int testDay ) const
{
   // determine whether testDay is valid for specified month
   if ( testDay > 0 && testDay <= daysInMonth( month ) )
      return testDay;
   // February 29 check for leap year 
   if ( month == 2 && testDay == 29 && isLeapYear() )
      return testDay;
   cout << "Invalid day (" << testDay << ") set to 1.\n";
   return 1; // leave object in consistent state if bad value
} // end function checkDay
// return the number of days in a month
int Date::daysInMonth( int m ) const
{
   if ( isLeapYear() && m == 2 )
      return 29;

   static const int daysPerMonth[ 13 ] = 
      { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
   return daysPerMonth[ m ];
} // end function daysInMonth
// test for a leap year
bool Date::isLeapYear() const
{
   if ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) )
      return true;
   else
      return false;
} // end function isLeapYear
// calculate 3-digit day based on Date object's current month and day
int Date::convertDDToDDD() const
{
   int ddd = 0;
   // for each month that has passed, add days to ddd
   for ( int i = 1; i < month; i++ )
      ddd += daysInMonth( i );

   // add days from current month
   ddd += day;
   return ddd;
} // end function convertDDToDDD
// set month and day based on 3-digit day
void Date::setMMDDFromDDD( int ddd )
{
   int dayTotal = 0;
   int m;
   for ( m = 1; m <= 12 && ( dayTotal + daysInMonth( m ) ) < ddd; m++ )
      dayTotal += daysInMonth( m );
   setMonth( m );
   setDay( ddd - dayTotal );
} // end function setMMDDFromDDD

// utility function to convert month number to month name
string Date::convertMMToMonth( int mm ) const
{
   static const string months[] = 
      { "", "January", "February", "March", "April", "May", "June", 
      "July", "August", "September", "October", "November", "December" };
   return months[ mm ];
} // end function convertMMToMonth
// set month number based on month name    
void Date::setMMFromMonth( string m )
{
   bool matchFound = false;
   // loop for each month, checking for a match
   for ( int i = 1; i <= 12 && !matchFound; i++ )
   {
      string tempMonth = convertMMToMonth( i );
      if ( tempMonth == m )
      {
         setMonth( i );
         matchFound = true;
      } // end if
   } // end for
   if ( !matchFound )
   {
      cout << "Invalid month name (" << month << "). month set to 1.\n";
      setMonth( 1 ); // leave object in consistent state if bad value
   } // end if
} // end function setMMFromMonth
// utility function to convert 4-digit year to 2-digit year
int Date::convertYYYYToYY() const
{
   // if year is in 2000s, subtract 2000
   // else, assume year is in the 1900s and subtract 1900
   return ( year >= 2000 ? year - 2000 : year - 1900 );
} // end function convertYYYYtoYY
// utility function to convert 2-digit year to 4-digit year
void Date::setYYYYFromYY( int yy )
{
   // if yy is less than 7, assume it is in the 2000s
   // if yy is greater than or equal to 7, assume it's in the 1900s
   year = ( yy < 7 ? yy + 2000 : yy + 1900 );
} // end function setYYYYFromYY
Main
#include <iostream> 
#include "Date.h" // include Date class definition
using namespace std;
int main()
{
   Date date1( 256, 1999 ); // initialize using ddd yyyy format
   Date date2( 3, 25, 04 ); // initialize using mm/dd/yy format
   Date date3( "September", 1, 2000 ); // "month" dd, yyyy format
   Date date4; // initialize to current date with default constructor
   // print Date objects in default format
   date1.print();
   date2.print();
   date3.print();
   date4.print();
   cout << '\n';
   // print Date objects in 'ddd yyyy' format
   date1.printDDDYYYY(); 
   date2.printDDDYYYY();
   date3.printDDDYYYY();
   date4.printDDDYYYY();
   cout << '\n';
   // print Date objects in 'mm/dd/yy' format
   date1.printMMDDYY(); 
   date2.printMMDDYY();
   date3.printMMDDYY();
   date4.printMMDDYY();
   cout << '\n';
   // print Date objects in '"month" d, yyyy' format
   date1.printMonthDDYYYY();
   date2.printMonthDDYYYY();
   date3.printMonthDDYYYY();
   date4.printMonthDDYYYY();
   cout << endl;
} // end main
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值