习题选自:C++ Primer Plus(第六版) 内容仅供参考,如有错误,欢迎指正 ! 1.创建函数-定义、提供原型和调用 2.两个恒等式:
arr[i] == *(arr + i)
&arr[i] == arr + i
3.默认情况下,C++函数按值传递参数,函数中的形参就是新的变量,它们被初始化为函数所提供的值(C++函数通过使用拷贝,保护了原数据的完整性)。
定义函数、提供函数、调用函数。
a. igor()没有参数,且没有返回值
b. tofu()接受一个int参数,并返回一个float
c. mpg()接受两个double参数,并返回一个double
d. summation()将long数组名和数组长度作为参数,并返回一个long值
e. doctor()接受一个字符串参数(不能修改该字符串),并返回一个double值
f. ofcourse()将boss结构作为参数,并返回一个字符串
g. plot()将map结构的指针作为参数,并返回一个字符串
a. void igor(void);
b. float tofu(int n);
c. double mpg(double m, double n);
d. long summation(long arr[], int size);
e. double doctor(const char* str);
f. char* ofcourse(boss bs);
g. char* plot(map *mp);
void setArrValue(int arr[], int size, int value)
{
for(int i = 0, i < size; i++)
{
arr[i] = value;
}
}
void setArr(int* begin,int *end, int value)
{
for(int* pt = begin; pt != end; pt++)
{
*pt = value;
}
}
double OutMaxValue(const double arr[], int size)
{
double max;
if(size < 1)
{
cout << "Array size is INVALID!" << endl;
cout << "will return 0."
return 0;
}
else
{
max = arr[0];
for(int i =0; i < size; i++)
{
if(max < arr[i])
max = arr[i];
}
return 0;
}
}
因为函数在调用参数时,使用的是参数的副本,不是原来的值,因此不会修改作为实参的基本类型的值,原数据就得到了保护。但是对于指针,需要使用const来防止指向的原始数据被修改。
字符串可以存储在char数组中,可以用带双引号的字符串来表示,也可以用指向字符串第一个字符的指针表示。
int replace(char * str, char c1, char c2)
int replance(char*str, char c1, char c2)
{
int count = 0;
while(*str)
{
if(*str == c1)
{
*str = c2;
count++;
}
str++;
}
return count;
}
c++将*"pizza"
中"pizza"解释为其第一个元素的地址,在使用*运算符将得到第一个元素的值,即字符p。c++将"taco"解释为其第一个元素的地址,因此它将"taco[2]"解释为第2个元素的值,即字符c。(注:字符常量的行为与数组名相同)
如果要按值传递,只需要传递结构名glitz即可。若传递地址,需要使用地址运算符&glitz。按值传递可以保护原始数据,但是牺牲内存和时间为代价。按地址传递可以节省时间和内存,但是不能保护原始数据,除非使用const限定符。(按值传递意味着可以使用常规的结构成员表示法,但传递指针必须使用间接成员运算符。)
int judge(int (*pf)(const char*))
struct applicant
{
char name[30];
int credit_ratings[3];
}
a.编写一个函数,将它的applicant结构作为参数,并显示该结构的的内容。 b.编写一个函数,将applicant结构作的地址作为参数,并显示该结构的内容。
//a.applicant结构作为参数
void display(applicant ap)
{
cout << ap.name << endl;
for(int i = 0; i < 3; i++)
{
cout << ap.credit_ratings[i] << endl;
}
}
//b.applicant结构的地址作为参数
void display(applicant *ap)
{
cout << ap->name << endl;
for(int i = 0; i < 3; i++)
{
cout << ap->credit_ratings[i] << endl;
}
}
void f1(applicant *a)
const char * f2(const applicant *a1, const applicant *a2)
typedef void (* pf1) (applicant *a);
typedef void (* pf2) (const applicant *a1, const applicant *a2);
pf1 p1 = f1;
pf2 p2 = f2;
pf1 ap[5];
pf2 (*pa)[10];
调和平均数=2.0*x*y/(x+y)
代码实现:
#include<iostream>
using namespace std;
double calculateHarmonicMean(double x, double y);
int main()
{
double a, b;
cout << "Please enter two numbers (if one is zero, stop):";
cin >> a;
cin >> b;
while (a && b)
{
cout << "Harmonic mean of " << a << " and " << b << " = " << calculateHarmonicMean(a, b) << endl;
cout << "Enter agen(if one is zero, stop):";
(cin >> a) >> b;
}
system("pause");
return 0;
}
double calculateHarmonicMean(double x, double y)
{
return 2.0 * x * y / (x + y);
}
代码实现:
#include<iostream>
using namespace std;
double SCORES[10];
int fillScore(double* score);
void display(double* score, int n);
double getAverage(double* score, int n);
int main()
{
double scores[10] = { 0 };
int n = fillScore(scores);
display(scores, n);
cout << "AVERAGESCORE: " << getAverage(scores, n) << endl;
system("pause");
return 0;
}
int fillScore(double* score)
{
cout << "Please enter the scores(maximum quantity=10),"<< endl;
cout << "If you want to end the input, enter a letter!" << endl;
double value;
int i;
for (i = 0; i < 10; i++)
{
cout << "enter the " << i + 1 << " Score:";
if (i > 9)
break;
else
{
if (cin >> value)
score[i] = value;
else
break;
}
}
cout << "QUANTITY: " << i << endl;
return i;
}
void display(double* score, int n)
{
cout << "SCORES: ";
for (int i = 0; i < n; i++)
cout << score[i] << " ";
cout << endl;
}
double getAverage(double* score, int n)
{
double sum=0;
for (int i = 0; i < n; i++)
sum += score[i];
return sum / n;
}
struct box
{
char marker[40];
float height;
float width;
float length;
float volume;
};
代码实现:
#include<iostream>
using namespace std;
struct box
{
char marker[40];
float height;
float width;
float length;
float volume;
};
void calculationBoxVolume(box* pbox);
void display(box bx);
int main()
{
box bx = { "jianmo1993",1.0,1.0,1.0,0.0 };
calculationBoxVolume(&bx);
display(bx);
system("pause");
return 0;
}
void display(box bx)
{
cout << "BOX'S INFORMATION:" << endl;
cout << "maker : " << bx.marker << endl;
cout << "height : " << bx.height << endl;
cout << "width : " << bx.width << endl;
cout << "length : " << bx.length << endl;
cout << "volume : " << bx.volume << endl;
}
void calculationBoxVolume(box* pbox)
{
pbox->volume = pbox->height * pbox->length * pbox->width;
}
代码实现:
#include<iostream>
using namespace std;
long double probability(unsigned numbers, unsigned picks);
int main()
{
long double result1,result2, result;
result1 = probability(47, 5);
result2 = probability(27, 1);
result = result1 * result2;
cout << "Odds of lottery jackpot : " << result << endl;
system("pause");
return 0;
}
long double probability(unsigned numbers, unsigned picks)
{
long double result = 1.0;
unsigned n, p;
for (n = numbers, p = picks; p > 0; n--, p--)
{
result = result * p / n;
}
return result;
}
代码实现:
#include<iostream>
using namespace std;
long factorial(long n);
int main()
{
long n;
cout << "CALCULATION OF FACTORIAL" << endl;
cout << "Enter number : ";
while (cin >> n)
{
long result = factorial(n);
cout << n << "! = " << result << endl;
cout << "Next number(q to quit):";
}
cout << "Bye!" << endl;
system("pause");
return 0;
}
long factorial(long n)
{
if (n == 1 || n == 0)
return 1;
else
return n * factorial(n - 1);
}
代码实现:
#include<iostream>
using namespace std;
const int n = 5;
int Fill_array(double* arr, int n);
void Show_array(double* arr, int n);
void Reverse_array(double* arr, int n);
int main()
{
double arr[n] = { 0.0 };
Fill_array(arr, n);
Show_array(arr, n);
Reverse_array(arr, n);
Show_array(arr, n);
system("pause");
return 0;
}
int Fill_array(double* arr, int n)
{
cout << "Please enter double number : ";
int i;
for (i = 0; i < n; i++)
{
if (cin >> arr[i])
{
cout << "Enter next number : ";
}
else
{
cout << "Type enter error!" << endl;
}
}
return i;
}
void Show_array(double* arr, int n)
{
cout << "ARRAY MEMBER : ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void Reverse_array(double* arr, int n)
{
int med = n / 2;
double temp;
for (int i = 0; i < med; i++)
{
temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
}
清单7.7:
/*******************************-清单7.7********************************/
// arrfun3.cpp -- array functions and const
#include <iostream>
const int Max = 5;
// function prototypes
int fill_array(double ar[], int limit);
void show_array(const double ar[], int n); // don't change data
void revalue(double r, double ar[], int n);
int main()
{
using namespace std;
double properties[Max];
int size = fill_array(properties, Max);
show_array(properties, size);
if (size > 0)
{
cout << "Enter revaluation factor: ";
double factor;
while (!(cin >> factor)) // bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; Please enter a number: ";
}
revalue(factor, properties, size);
show_array(properties, size);
}
cout << "Done.\n";
// cin.get();
// cin.get();
return 0;
}
int fill_array(double ar[], int limit)
{
using namespace std;
double temp;
int i;
for (i = 0; i < limit; i++)
{
cout << "Enter value #" << (i + 1) << ": ";
cin >> temp;
if (!cin) // bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
else if (temp < 0) // signal to terminate
break;
ar[i] = temp;
}
return i;
}
// the following function can use, but not alter,
// the array whose address is ar
void show_array(const double ar[], int n)
{
using namespace std;
for (int i = 0; i < n; i++)
{
cout << "Property #" << (i + 1) << ": $";
cout << ar[i] << endl;
}
}
// multiplies each element of ar[] by r
void revalue(double r, double ar[], int n)
{
for (int i = 0; i < n; i++)
ar[i] *= r;
}
/**********************************************************************/
代码实现:
/*******************************-清单7.7********************************/
#include <iostream>
const int Max = 5;
// function prototypes
double* fill_array(double* begin, double* end);
void show_array(double* begin, double* end); // don't change data
void revalue(double r, double* start, double* end);
int main()
{
using namespace std;
double properties[Max];
double* end = fill_array(properties, properties + Max - 1);
show_array(properties, end);
if ((end - properties) > 0)
{
cout << "Enter revaluation factor: ";
double factor;
while (!(cin >> factor)) // bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; Please enter a number: ";
}
revalue(factor, properties, end);
show_array(properties, end);
}
cout << "Done.\n";
// cin.get();
// cin.get();
return 0;
}
double* fill_array(double* begin, double* end)
{
using namespace std;
double* temp;
int i = 0;
for (temp = begin; temp <= end; temp++)
{
cout << "Enter value #" << (i + 1) << ": ";
cin >> *temp;
if (!cin) // bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
else if (*temp < 0) // signal to terminate
break;
}
return temp - 1;
}
void show_array(double* begin, double* end)
{
using namespace std;
double* p;
int i = 0;
for (p = begin; p <= end; p++)
{
cout << "Property #" << (i + 1) << ": $";
cout << *p << endl;
}
}1
void revalue(double r, double* start, double* end)
{
double* p;
for (p = start; p <= end; p++)
*p *= r;
}
清单7.15:
//arrobj.cpp -- functions with array objects
#include <iostream>
#include <array>
#include <string>
const int Seasons = 4;
const std::array<std::string, Seasons> Snames =
{"Spring", "Summer", "Fall", "Winter"};
void fill(std::array<double, Seasons> * pa);
void show(std::array<double, Seasons> da);
int main()
{
std::array<double, 4> expenses;
fill(&expenses);
show(expenses);
// std::cin.get();
// std::cin.get();
return 0;
}
void fill(std::array<double, Seasons> * pa)
{
for (int i = 0; i < Seasons; i++)
{
std::cout << "Enter " << Snames[i] << " expenses: ";
std::cin >> (*pa)[i];
}
}
void show(std::array<double, Seasons> da)
{
double total = 0.0;
std::cout << "\nEXPENSES\n";
for (int i = 0; i < Seasons; i++)
{
std::cout << Snames[i] << ": $" << da[i] << '\n';
total += da[i];
}
std::cout << "Total: $" << total << '\n';
}
/********************************************************************/
代码实现:
a.
#include <iostream>
#include <array>
#include <string>
const int Seasons = 4;
const char* Snames[Seasons] =
{ "Spring", "Summer", "Fall", "Winter" };
void fill(double* pa, int n);
void show(double* da, int n);
int main()
{
double expenses[Seasons];
fill(expenses, Seasons);
show(expenses, Seasons);
return 0;
}
void fill(double* pa, int n)
{
for (int i = 0; i < n; i++)
{
std::cout << "Enter " << Snames[i] << " expenses: ";
std::cin >> pa[i];
}
}
void show(double* da, int n)
{
double total = 0.0;
std::cout << "\nEXPENSES\n";
for (int i = 0; i < n; i++)
{
std::cout << Snames[i] << ": $" << da[i] << '\n';
total += da[i];
}
std::cout << "Total: $" << total << '\n';
}
b.
#include <iostream>
#include <array>
#include <string>
const int Seasons = 4;
const char* Snames[Seasons] =
{ "Spring", "Summer", "Fall", "Winter" };
struct Expenses
{
double expenses[Seasons];
};
void fill(Expenses* exp, int n);
void show(Expenses* exp, int n);
int main()
{
Expenses expenses;
fill(&expenses, Seasons);
show(&expenses, Seasons);
return 0;
}
void fill(Expenses* exp, int n)
{
double* pa = exp->expenses;
for (int i = 0; i < n; i++)
{
std::cout << "Enter " << Snames[i] << " expenses: ";
std::cin >> pa[i];
}
}
void show(Expenses* exp, int n)
{
double* da = exp->expenses;
double total = 0.0;
std::cout << "\nEXPENSES\n";
for (int i = 0; i < n; i++)
{
std::cout << Snames[i] << ": $" << da[i] << '\n';
total += da[i];
}
std::cout << "Total: $" << total << '\n';
}
#include <iostream>
using namespace std;
const int SLEN = 30;
struct student {
char fullname[SLEN];
char hobby[SLEN];
int ooplevel;
};
// getinfo() has two arguments: a pointer to the first element of
// an array of student structures and an int representing the
// number of elements of the array. The function solicits and
// stores data about students. It terminates input upon filling
// the array or upon encountering a blank line for the student
// name. The function returns the actual number of array elements
// filled.
int getinfo(student pa[], int n);
// display1() takes a student structure as an argument
// and displays its contents
void display1(student st);
// display2() takes the address of student structure as an
// argument and displays the structure’s contents
void display2(const student* ps);
// display3() takes the address of the first element of an array
// of student structures and the number of array elements as
// arguments and displays the contents of the structures
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;
}
代码实现:
#include <iostream>
using namespace std;
const int SLEN = 30;
struct student {
char fullname[SLEN];
char hobby[SLEN];
int ooplevel;
};
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 num = 0;
for (int i = 0; i < n; i++)
{
cout << "Enter #" << i + 1 << " student' info:" << endl;
cout << "fullname : ";
cin.getline(pa[i].fullname, SLEN);
if (pa[i].fullname[0] == '\0')
break;
cout << "hobby : ";
cin.getline(pa[i].hobby, SLEN);
cout << "ooplevel : ";
(cin >> pa[i].ooplevel).get();
num++;
}
return num;
}
void display1(student st)
{
cout << "name: " << st.fullname << endl;
cout << "hobby: " << st.hobby << endl;
cout << "ooplevel: " << st.ooplevel << endl;
}
void display2(const student* ps)
{
cout << "name: " << ps->fullname << endl;
cout << "hobby: " << ps->hobby << endl;
cout << "ooplevel: " << ps->ooplevel << endl;
}
void display3(const student pa[], int n)
{
for(int i = 0; i < n; i++)
{
display2(&pa[i]);
}
}
double add (double x, double y)
{
return x + y;
}
double q = calculate (2.5, 10.4, add);
double (*pf[3]) (double, double);
代码实现:
#include <iostream>
using namespace std;
typedef double (*pfunc)(double x, double y);
double add(double x, double y);
double multiply(double x, double y);
double calculate(double x, double y, pfunc pf);
int main()
{
pfunc pf[2] = {add, multiply};
cout << "Please enter two numbers : ";
double a, b;
while ((cin >> a) >> b)
{
for (int i = 0; i < 2; i++)
{
cout << a;
if(i == 0)
cout << " + ";
else
cout << " * ";
cout << b << " = " << pf[i](a, b) << endl;
}
cout << "Next two numbers(q to quit) : ";
}
return 0;
}
double add(double x , double y)
{
return x + y;
}
double multiply(double x, double y)
{
return x * y;
}
double calculate(double x, double y, pfunc pf)
{
return pf(x, y);
}