C++ Primer Plus(第6版)中文版部分答案
5.8
#include<iostream>
#include<cstring>
int main(void)
{
using namespace std;
char word[20];
int i = 0;
cout << "Enter words(to stop,type the word done)\n";
cin >> word;
while (strcmp(word, "done"))
{
cin >> word;
i++;
}
cout << "You entered a total of " << i << " words";
}
5. 9
#include<iostream>
#include<string>
int main(void)
{
using namespace std;
string word;
int i = 0;
cout << "Enter words(to stop,type the word done)\n";
cin >> word;
while (word != "done")
{
cin >> word;
i++;
}
cout << "You entered a total of " << i << " words";
}
5.10
#include<iostream>
int main(void)
{
using namespace std;
int num;
cout << "Please input a number: ";
cin >> num;
for (int i = 1; i < num + 1; i++)
{
for (int j = 0; j < (num - i); j++)
cout << ".";
for (int k = 0; k < i; k++)
cout << "*";
cout << endl;
}
}
7.6填充数组,反转数组,显示数组
#include<iostream>
int fill_array(double ar[],int n);
void show_array(const double ar[],int n);
void reverse_array(double ar[],int n);
int main()
{
using namespace std;
double scores[10];
int num = fill_array(scores,10);
// cout << num << endl << scores[2];
show_array(scores,num);
//reverse_array(scores,num);
show_array(scores,num);
reverse_array(&(scores[1]),num-2);
show_array(scores,num);
}
int fill_array(double ar[],int n)
{
using namespace std;
int count = 0;
for(int i = 0;i < n;i++)
{
cout << "Please input " << i+1 << " number:";
double x;
if(cin >> x)
{
ar[i] = x;
count++;
}
else
break;
}
return count;
}
void show_array(const double ar[],int n)
{
using namespace std;
for(int i = 0;i < n;i++)
{
cout << i + 1 << ": " << ar[i] << endl;
}
}
void reverse_array(double ar[],int n)
{
double t;
for(int i = 0,j = n-1;i < j;i++,j--)
{
t = ar[i];
ar[i] = ar[j];
ar[j] = t;
}
}
7.10 指向函数的指针
#include<iostream>
double add (double,double);
double calculate(double,double,double (*pf)(double,double));
double subtract (double x,double y);
double multiply (double x,double y);
double divide (double x,double y);
int main()
{
//std::cout << calculate(5.5,4.2,add);
double (*pf[4])(double,double) = {add,subtract,multiply,divide};
for(int i = 0;i < 4;i++)
{
std::cout << calculate(7.6,3.8,*(pf[i])) << std::endl;
}
}
double add (double x,double y)
{
return x + y;
}
double subtract (double x,double y)
{
return x - y;
}
double multiply (double x,double y)
{
return x * y;
}
double divide (double x,double y)
{
return x / y;
}
double calculate(double m,double n,double (*pf)(double,double))
{
return pf(m,n);
}