PS:自学C++ PrimerPlus (第6版)中,程序每章习题集中在一起,运行时每次注释 main 函数中的 test 即可。如有错误或者效率低的地方欢迎指出,有疑问也欢迎一起讨论。
第4章练习题答案
#include<string>
#include<iostream>
#include<sstream>
#include<vector>
#include<iomanip>
#include<cstring>
#include<array>
using namespace std;
void test1()
{
struct MyInfo
{
string first_name;
string last_name;
char grade{'A'};
int age=0;
}LiMing;
cout << "What is your first name? ";
getline(cin, LiMing.first_name);
cout << "What is your last name? ";
getline(cin, LiMing.last_name);
cout << "What letter grade do you deserve? ";
cin >> LiMing.grade;
cout << "What is your age? ";
cin >> LiMing.age;
cout << "Name: " << LiMing.last_name << ", " << LiMing.first_name << endl;
cout << "Grade: " << char(LiMing.grade + 1) << endl;
cout << "Age: " << LiMing.age << endl;
}
void test2()
{
string name;
string dessert;
cout << "Enter your name: \n";
getline(cin, name);
cout << "Enter your favorite dessert: \n";
getline(cin, dessert);
cout << "I have some delicious " << dessert << " for you, " << name << ".\n";
}
void test3_4()
{
//char first_name1[30];
//char last_name1[30];
string first_name2;
string last_name2;
cout << "Enter your first name: ";
//cin.getline(first_name1,30);
getline(cin, first_name2);
cout << "Enter your last name: ";
//cin.getline(last_name1,30);
getline(cin, last_name2);
//char name1[65] = {};
//char connect[3] = { ',', ' ','\0' };
string name2 = "";
//strcpy_s(name1, sizeof(name1), last_name1);
//strcat_s(name1, sizeof(name1), connect);
//strcat_s(name1, sizeof(name1), first_name1);
name2 = last_name2 + ", " + first_name2;
cout << "Here's the information in a single string: " << name2 << endl;
}
void test5_6_9()
{
struct CandyBar {
string brand = "Mocha Munch";
double weight = 2.3;
unsigned int calorie = 350;
}snack;
cout << snack.brand << endl;
cout << snack.weight << endl;
cout << snack.calorie << endl;
CandyBar candy[3];
candy[0].brand = "a";
candy[0].weight = 0.5;
candy[0].calorie = 120;
cout << candy[0].brand << ", " << candy[0].weight << ", " << candy[0].calorie << endl;
candy[1].brand = "b";
candy[1].weight = 0.8;
candy[1].calorie = 200;
cout << candy[1].brand << ", " << candy[1].weight << ", " << candy[1].calorie << endl;
candy[2].brand = "c";
candy[2].weight = 0.9;
candy[2].calorie = 340;
cout << candy[2].brand << ", " << candy[2].weight << ", " << candy[2].calorie << endl;
cout << "----------------test9----------------" << endl;
CandyBar* pt = new CandyBar[3];
pt->brand = "a1";
pt->weight = 0.5;
pt->calorie = 120;
cout << pt->brand << ", " << pt->weight << ", " << pt->calorie << endl;
(pt+1)->brand = "b1";
(pt + 1)->weight = 0.8;
(pt + 1)->calorie = 200;
cout << (pt + 1)->brand << ", " << (pt + 1)->weight << ", " << (pt + 1)->calorie << endl;
(pt + 2)->brand = "c1";
(pt + 2)->weight = 0.9;
(pt + 2)->calorie = 340;
cout << (pt + 2)->brand << ", " << (pt + 2)->weight << ", " << (pt + 2)->calorie << endl;
delete[] pt;
}
void test7_8()
{
struct piza
{
string company = "a";
double diameter = 1;
double weight = 2.5;
}piza1;
cout << "Enter the company of piza1: ";
cin >> piza1.company;
cout << "Enter the diameter: ";
cin >> piza1.diameter;
cout << "Enter the weight: ";
cin >> piza1.weight;
cout << "You enter:" << piza1.company << ", " << piza1.diameter << ", " << piza1.weight << endl;
cout << "-------------test8--------------" << endl;
piza* p = new piza;
cout << "Enter the diameter: ";
cin >> p->diameter;
cout << "Enter the company of piza1: ";
cin >> p->company;
cout << "Enter the weight: ";
cin >> p->weight;
cout << "You enter:" << p->diameter << ", " << p->company << ", " << p->weight << endl;
delete p;
}
void test10()
{
array<int, 3> score;
cout << "Enter the first score: ";
cin >> score[0];
cout << "Enter the second score: ";
cin >> score[1];
cout << "Enter the third score: ";
cin >> score[2];
cout << score.size() << "次的平均分为:" << (score[0] + score[1] + score[2]) / score.size() << endl;
}
int main()
{
//test1();
//test2();
//test3_4()
//test5_6_9();
//test7_8();
test10();
return 0;
}
第5章练习题答案
#include<iostream>
#include<array>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
void test1()
{
int a, b;
cout << "Enter the first integer: ";
cin >> a;
cout << "Enter the second integer: ";
cin >> b;
int sum = 0;
while (a <= b)
{
sum += a;
a++;
}
cout << "The sum of two number is " << sum << ".\n";
}
void test2()
{
array<long double, 101> factorials;
factorials[1] = factorials[0] = 1L;
for (int i = 2; i < 101; i++)
factorials[i] = i * factorials[i - 1];
std::cout << 100 << "! = " << factorials[100] << std::endl;
}
void test3()
{
int temp = 0;
int integer;
do
{
cout << "Enter an integer: ";
cin >> integer;
temp += integer;
} while (integer);
cout <<"The sum of these numbers is "<< temp << endl;
}
void test4()
{
int year;
for (year = 1; (100 + 10 * year) > (100 * pow(1.05, year)); year++);
cout << year << "年后,Cleo的投资价值大于Daphne." << endl;
cout << "Daphne:" << (100 + 10 * year) << ".\n";
cout << "Cleo: " << 100 * pow(1.05, year) << ".\n";
}
void test5()
{
string month[12]{"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
int sales_volume[12];
int sum = 0;
for (int i=0;i<12;i++)
{
cout << month[i] << ": ";
cin >> sales_volume[i];
sum += sales_volume[i];
}
cout << "total sale volume: " << sum << endl;
}
void test6()
{
string month[12]{ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
int sales_volume[3][12];
int sum[3] = { 0 };
for (int j = 0; j < 3; j++)
{
cout << "请输入第" << j << "年每个月的销量.\n";
for (int i = 0; i < 12; i++)
{
cout << month[i] << ": ";
cin >> sales_volume[j][i];
sum[j] += sales_volume[j][i];
}
cout<<"第" <<j+1<< "的销量: " << sum[j] << endl;
}
cout << "3年总销量: " << sum[0]+sum[1]+sum[2] << endl;
}
void test7()
{
struct car {
string manufacturer;
int production_year;
};
int num;
cout << "How many cars do you want to catalog? ";
cin >> num;
cin.get();//去除回车符
car* p = new car [num];
for (int i = 0; i < num;i++)
{
cout << "Car #" << i+1 << ": \n";
cout << "Please enter the maker: ";
getline(cin, (p + i)->manufacturer);
cout << "Please enter the year made: ";
cin >> (p + i)->production_year;
cin.get();//去除回车符
}
cout << "Here is your collection:\n";
for (int i = 0; i < num; i++)
{
cout << (p + i)->production_year << " " << (p + i)->manufacturer << endl;
}
delete [] p;
}
void test8()
{
cout << "Enter words (to stop, type the word done):" << endl;
char word[256];
cin >> word;
int count = 0;
while (strcmp(word, "done"))
{
count += 1;
cin >> word;
}
cout << "You entered a total of " << count << " words." << endl;
}
void test9()
{
cout << "Enter words (to stop, type the word done):" << endl;
string word;
cin >> word;
int count = 0;
while (word != "done")
{
count += 1;
cin >> word;
}
cout << "You entered a total of " << count << " words." << endl;
}
void test10()
{
cout << "Enter number of rows: ";
int rows;
cin >> rows;
for (int i = 0; i < rows; i++)
{
for(int j = 0; j < rows; j++)
{
if( j >= rows - i - 1)
cout << "*";
else cout << ".";
}
cout << endl;
}
}
int main()
{
//test1();
//test2();
//test3();
//test4();
//test5();
//test6();
//test7();
//test8();
//test9();
test10();
}
第6章练习题答案
#include <iostream>
#include <cctype>
#include <array>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
void test1() {
char ch;
cout << "Enter the text, type @ to terminate.\n";
while ((ch=cin.get( )) && ch != '@') {
if (!isdigit(ch)) {
if (isupper(ch))
ch = tolower(ch);
else if(islower(ch))
ch = toupper(ch);
cout << ch;
}
}
}
void test2() {
const int Size = 10;
array <double, Size> donation{0};
int i = 0, num=0;
double sum=0,temp;
cout << "Enter the donation value, type char to terminate.\n";
while (cin >> temp && i < Size) {
donation[i] = temp;
sum += donation[i];
i++;
}
if (!cin) {
cout << "检测到非数字输入!" << endl;
}
double average = sum / i;
for (double x : donation) {
if (x > average)
num++;
}
cout << "You have input " << i << " numbers, and the average is " << average << ".\n";
cout << num << " numbers exceed the average." << endl;
}
void test3() {
char ch;
string str;
cout << "Please enter one of the following choice: \n";
cout << "c) carnivore\t\t p) pianist\nt) tree\t\t\t g) game\n";
bool flag = false;
while (!flag && cin >> ch) {
flag = true;
switch (ch) {
case 'C':
case 'c': str = "carnivore";
break;
case 'P':
case 'p': str = "pianist";
break;
case 'T':
case 't': str = "tree";
break;
case 'G':
case 'g': str = "game";
break;
default: cout << "Please enter a c, p, t, g: ";
flag = false;
break;
}
}
cout << "A maple is a " << str << endl;
}
void test4() {
const int strsize = 20;
struct bop {
char fullname[strsize]; //real name
char title[strsize]; //job title
char bopname[strsize]; //secret BOP name
int preference; //0=fullname, 1=title, 2=bopname
};
bop benevolents[5] = {
{"Wimp Macho","teacher","king",0},
{"Raki Rhodes","Junior Programmer","solder",1},
{"Celia Laiter","MIPS","MIPS",2},
{"Hoppy Hipman","Analyst Trainee","fly",1},
{"Pat hand","students","LOOPY",2},
};
cout << "Benevolent Order of Programmers Report: \n";
cout << "a) display by name\t b) display by title\nc) display by bopname\t d) dispaly by preference\nq) quit\n";
char ch;
bool flag = true;
cout << "Enter your choice: ";
while (flag && cin>>ch) {
switch (ch) {
case 'a':
for (bop x : benevolents) {
cout << x.fullname << endl;
} break;
case 'b':
for (bop x : benevolents) {
cout << x.title << endl;
} break;
case 'c':
for (bop x : benevolents) {
cout << x.bopname << endl;
} break;
case 'd':
for (bop x : benevolents) {
switch (x.preference){
case 0:cout << x.fullname << endl; break;
case 1:cout << x.title << endl; break;
case 2:cout << x.bopname << endl; break;
}
} break;
case 'q':flag = false;
cout << "Bye!" << endl;
break;
}
if (flag) {
cout << "Next choice: ";
}
}
}
void test5() {
int income;
double tax;
cout << "Please enter you income: \n";
while (cin >> income && income >= 0) {
if (income <= 5000) {
tax = 0;
}
else if (income >= 5001 && income <= 15000) {
tax = 5000 * 0.0 + (income - 5000) * 0.1;
}
else if (income >= 15001 && income <= 35000) {
tax = 5000 * 0.0 + 10000 * 0.1 + (income - 15000) * 0.15;
}
else if (income >= 35001) {
tax = 5000 * 0.0 + 10000 * 0.1 + 20000 * 0.15 + (income - 35000) * 0.20;
}
cout << "Your personal income tax is " << tax << "tvarp." << endl;
cout << "Enter you income:\n";
}
}
void test6() {
struct donors {
string name;
double funds;
};
cout << "Please enter the number of patrons: ";
int num;
cin >> num;
donors* p = new donors[num];
cout << "Please enter the name of patrons, and the funds.\n";
int i = 0;
while (i < num) {
cout << "#" << i + 1 << ": ";
cin >> (p + i)->name;
cin >> (p + i)->funds;
i++;
}
cout << "Below are some important patrons.\n";
int j1 = 0;
for (int i = 0; i < num; i++) {
if ((p + i)->funds > 10000) {
cout << (p + i)->name << "\t" << (p + i)->funds << endl;
j1++;
}
}
if (0 == j1) {
cout << "none!\n";
}
int j2 = 0;
cout << "other patrons:\n";
for (int i = 0; i < num; i++) {
if ((p + i)->funds <= 10000) {
cout << (p + i)->name << "\t" << (p + i)->funds << endl;
j2++;
}
}
if (0 == j2) {
cout << "none!\n";
}
}
void test7() {
cout << "Enter words (q to quit):\n";
vector<string> words{};
int i = 0;
int num_vowel = 0, num_consonant = 0, num_else = 0;
string word;
while ((cin >> word) && word != "q") {
words.push_back(word);
if (!isalpha(words[i][0])) {
num_else++;
}
else
{
switch (words[i][0]) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':num_vowel++; break;
default:num_consonant++; break;
}
}
i++;
}
cout << num_vowel << " words begining with vowels\n";
cout << num_consonant << " words begining with consonants\n";
cout << num_else << " others.\n";
}
void test8() {
string filename;
cout << "enter the filename you want to open: ";
cin >> filename;
ifstream inFile;
inFile.open(filename);
while (!inFile.is_open()) {
cout << "Could not open the file " << filename << endl;
cout << "Please cheack out the file.\n";
cout << "-----------------------------\n";
cout << "enter the filename again: ";
cin >> filename;
inFile.open(filename);
}
char ch;
int charCount = 0;
while (inFile.get(ch)) {
++charCount;
cout << ch;
}
inFile.close();
cout << "总字符数:" << charCount << endl;
}
void test9() {
struct donors {
string name;
double funds;
};
string filename;
cout << "enter the filename you want to open: ";
cin >> filename;
ifstream inFile;
inFile.open(filename);
while (!inFile.is_open()) {
cout << "Could not open the file " << filename << endl;
cout << "Please cheack out the file.\n";
cout << "-----------------------------\n";
cout << "enter the filename again: ";
cin >> filename;
inFile.open(filename);
}
string line;
//getline(inFile,line);第一种
//int num;
//num = stoi(line);
int num;
(inFile >> num).get();//第二种
cout << "人数:" << num << endl;
donors* p = new donors[num];
int i = 0, j = 0;
while (i < num) {
getline(inFile, (p + i)->name);
//getline(inFile, line);
//(p + i)->funds = stod(line); //第一种
(inFile >> (p + i)->funds).get();//第二种
i++;
}
inFile.close();
cout << "Below are some important patrons:\n";
int j1 = 0;
for (int i = 0; i < num; i++) {
if ((p + i)->funds > 10000) {
cout << (p + i)->name << "\t" << (p + i)->funds << endl;
j1++;
}
}
if (0 == j1) {
cout << "none!";
}
int j2 = 0;
cout << "other patrons:\n";
for (int i = 0; i < num; i++) {
if ((p + i)->funds <= 10000) {
cout << (p + i)->name << "\t" << (p + i)->funds << endl;
j2++;
}
}
if (0 == j2) {
cout << "none!";
}
}
int main() {
//test1();
//test2();
//test3();
//test4();
//test5();
//test6();
//test7();
//test8();
test9();
}
第7章练习题答案
#include <iostream>
#include <array>
#include <cstring>
using namespace std;
double harmonic_mean(double x, double y) {
return 2.0 * x * y / (x + y);
}
void test1() {
double a, b;
cout << "Please enter two number(enter 0 to quit): ";
while (cin >> a && 0 != a && cin>> b && 0 != b) {
cout << "The harmonic mean of " << a << " and " << b << " is " << harmonic_mean(a, b) << endl;
cout << "\nPlease enter two number(enter 0 to quit): ";
}
}
//------------------------------------------------------test2
const int max_size = 10;
int input_array(double a[], int b) {
cout << "You can enter up to 10 scores(enter q to quit): ";
int count = 0;
while (count< max_size && cin >> a[count]) {
count++;
if (10 == count)
break;
cout << "Next score: ";
}
return count;
}
void show_score(double a[], int b) {
cout << "You enter socre: ";
for (int i = 0; i < b; i++) {
cout << a[i] << " ";
}
}
void caculate_score(double a[], int b) {
double sum = 0;
for (int i = 0; i < b; i++)
sum += a[i];
double mean = sum / b;
cout << "\nThe average of these score is " << mean << ".\n";
}
void test2() {
double score[max_size];
int real_size = input_array(score, max_size);
show_score(score, real_size);
caculate_score(score, real_size);
}
//---------------------------------------------test3
struct box {
char maker[40];
float height;
float width;
float length;
float volume;
};
void show_box(box a) {
cout << "maker: " << a.maker << endl;
cout << "height: " << a.height << endl;
cout << "width: " << a.width << endl;
cout << "length: " << a.length << endl;
cout << "volume: " << a.volume << endl;
}
void calculate_box(box *p) {
p->volume = p->length * p->height * p->width;
}
void test3() {
box a{ "rectangle",3.0, 2.0, 1.2, 0 };
show_box(a);
calculate_box(&a);
cout << "The volume of the box is " << a.volume << endl;
}
//---------------------------------------------------test4
long double probability(unsigned numbers, unsigned picks)
{
long double result = 1.0;
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p;
return result;
}
void test4() {
long double re = probability(47, 5) * probability(27, 1);
cout << "The probability of you winning the jackpot is " << 1/re;
}
//---------------------------------------------------test5
unsigned long long fun1(int i) {
unsigned long long re = 0;
if (0 == i ) {
re = 1;
}
else if (i>0) {
re = i * fun1(i - 1);
}
return re;
}
void test5() {
cout << "Please enter a positive integer (negative to quit):\n";
int integer;
while (cin>>integer) {
if (integer < 0) {
break;
}
unsigned long long re = fun1(integer);
cout << integer << "! = " << re << endl;
cout << "Enter another positive integer (negative to qiut): \n";
}
cout << "exit...\n";
}
//---------------------------------------------------test6
int Fill_array(double* p, int size) {
cout << "Enter a double value: ";
double temp;
int i = 0;
while (i < size && cin >> temp) {
*(p+i) = temp;
i++;
}
return i;
}
void Show_array(double* p, int size) {
for (int i = 0; i < size; i++) {
cout << *(p + i)<<" ";
}
cout << endl;
}
void Reverse_array(double* p, int size) {
double temp;
for (int i = 0; i < size - i; i++) {
temp = *(p + i);
*(p + i) = *(p + size - i - 1);
*(p + size - i - 1) = temp;
}
}
void test6() {
const int max_size = 5;
double array[max_size];
int size = Fill_array(array, max_size);
cout << "You enter: ";
Show_array(array, size);
Reverse_array(array, size);
cout << "reverse array: ";
Show_array(array, size);
Reverse_array(array+1, size-2);
cout << "reverse part of array: ";
Show_array(array, size);
}
//---------------------------------------------------test7
double * fill_array(double *p, double *j)
{
double temp;
int i;
for (i = 0; p+i < j; 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;
*(p+i) = temp;
}
return p+i;
}
void show_array(double* p, double* j)
{
for (int i = 0; p + i < j; i++)
{
cout << "Property #" << (i + 1) << ": $";
cout << *(p+i) << endl;
}
}
void revalue(double r, double* p, double* j)
{
for (int i = 0; p+i < j; i++)
*(p+i) *= r;
}
void test7() {
const int Max = 5;
double properties[Max];
double * size = fill_array(properties, properties + Max);
show_array(properties, size);
if ((size-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, size);
show_array(properties, size);
}
cout << "Done.\n";
}
//---------------------------------------------------test8-a
const int Seasons = 4;
const char* Snames[Seasons] =
{ "Spring", "Summer", "Fall", "Winter" };
void fill(double *pa)
{
for (int i = 0; i < Seasons; i++)
{
std::cout << "Enter " << *(Snames+i) << " expenses: ";
std::cin >> *(pa+i);
}
}
void show(double * 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';
}
void test8_a() {
double expenses[4];
fill(expenses);
show(expenses);
}
//---------------------------------------------------test8-b
struct cost {
double expenses[4];
}cost_all;
void fill_b(cost* pa)
{
for (int i = 0; i < Seasons; i++)
{
std::cout << "Enter " << *(Snames + i) << " expenses: ";
std::cin >> (pa->expenses)[i];
}
}
void show_b(cost* da)
{
double total = 0.0;
std::cout << "\nEXPENSES\n";
for (int i = 0; i < Seasons; i++)
{
std::cout << Snames[i] << ": $" << (da->expenses)[i] << '\n';
total += (da->expenses)[i];
}
std::cout << "Total: $" << total << '\n';
}
void test8_b() {
fill_b(&cost_all);
show_b(&cost_all);
}
//---------------------------------------------------test9
const int SLEN = 30;
struct student {
char fullname[SLEN];
char hobby[SLEN];
int ooplevel;
};
int getinfo(student pa[], int n) {
char temp[SLEN];
int level = 0;
int i = 0;
for (i = 0; i < n; i++) {
cout << "#" << i + 1 << endl;
cout << "Enter the name: ";
cin.getline(temp, SLEN);
if ('\0' == temp[0])
break;
strcpy_s((pa + i)->fullname, temp);
cout << "Enter the hobby: ";
cin.getline(temp, SLEN);
strcpy_s((pa + i)->hobby, temp);
cout << "Enter the ooplevel: ";
while (!(cin >> level)) { // 确保输入的是整数
cout << "Invalid input. Please enter an integer: ";
cin.clear(); // 清除错误标志
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // 忽略无效输入
}
(pa + i)->ooplevel = level;
cin.get();
}
return i;
}
void display1(student st) {
cout << "fullname: " << st.fullname << endl;
cout << "hobby: " << st.hobby << endl;
cout << "ooplevel: " << st.ooplevel << endl;
}
void display2(const student *ps) {
cout << "fullname: " << 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++) {
cout << "fullname: " << pa->fullname << endl;
cout << "hobby: " << pa->hobby << endl;
cout << "ooplevel: " << pa->ooplevel << endl;
}
}
void test9() {
cout << "Enter class size: ";
int class_size;
cin >> class_size;
while (cin.get() != '\n')
continue;
student* pre_stu = new student[class_size];
int entered = getinfo(pre_stu, class_size);
for (int i = 0; i < entered; i++) {
display1(pre_stu[i]);
display2(&pre_stu[i]);
}
display3(pre_stu, entered);
delete[]pre_stu;
cout << "Done\n";
}
//---------------------------------------------------test10
double calculate(double a, double b, double (*fun)(double, double)) {
return fun(a, b);
}
double add(double x,double y) {
double re = x + y;
cout << x << " + " << y << " = " << re << endl;
return re;
}
double multiply(double x, double y) {
double re = x * y;
cout << x << " * " << y << " = " << re << endl;
return re;
}
double subtract(double x, double y) {
double re = x - y;
cout << x << " - " << y << " = " << re << endl;
return re;
}
double(*pf[3])(double, double) = {add,multiply,subtract};
void test10() {
double a, b;
cout << "enter two double value: ";
cin >> a >> b;
for (int i = 0; i < 3; i++) {
double q = calculate(a, b, (*pf[i]));
}
}
int main() {
//test1();
//test2();
//test3();
//test4();
//test5();
//test6();
//test7();
//test8_a();
//test8_b();
//test9();
test10();
}
第8章练习题答案
#include <iostream>
#include <string>
#include <cctype>
#include <cstring>
using namespace std;
// -------------------------------------------------test1
int count1 = 0;
void show(const char* str, int n = 0) {
count1++;
if (0 == n)
cout << str << endl;
else {
for (int i = 0; i < count1; i++)
cout << str << " ";
cout << endl;
}
}
void test1() {
const int size = 100;
cout << "Enter a string: ";
char str[size];
cin.getline(str, size);
for (int i = 0; i < 3; i++) {
show(str);
show(str, 2);
}
}
// -------------------------------------------------test2
struct CandyBar {
string brand;
float weight;
int calories;
};
void set_candybar(CandyBar& candy, const char* str = "Millennium Munch",
double candy_weight = 2.85, int candy_calories = 350) {
candy.brand = str;
candy.weight = candy_weight;
candy.calories = candy_calories;
}
void show_candybar(const CandyBar& candy) {
cout << "---\n";
cout << "brand: " << candy.brand << endl;
cout << "weight: " << candy.weight << endl;
cout << "calories: " << candy.calories << endl;
}
void test2() {
CandyBar my_candy;
char brand[50];
float weight;
int calories;
cout << "Enter the brand of your candy: " ;
cin.getline(brand,50);
cout << "Enter the weight of your candy: " ;
cin >> weight;
cout << "Enter the calories of your candy: " ;
cin >> calories;
set_candybar(my_candy, brand);
show_candybar(my_candy);
set_candybar(my_candy, brand, weight);
show_candybar(my_candy);
set_candybar(my_candy, brand, weight, calories);
show_candybar(my_candy);
}
// -------------------------------------------------test3
void to_upper(string& str) {
for (char &x : str)
x = toupper(x);
cout << str << endl;
}
void test3() {
cout << "Enter a string (q to quit): ";
string str;
getline(cin, str);
while ("q" != str && "Q" != str) {
to_upper(str);
cout << "Next string (q to quit):";
getline(cin, str);
}
cout << "Bye." << endl;
}
// -------------------------------------------------test4
struct stringy {
char* str;
int ct; //length of string(not counting "\0")
};
void set(stringy& stry, char* str_temp) {
stry.ct = strlen(str_temp);
stry.str = new char[stry.ct + 1];
strcpy_s(stry.str, stry.ct+1, str_temp);
}
void show4(const stringy &stry, int ct = 1) {
while (ct) {
cout << stry.str << endl;
ct--;
}
}
void show4(const char* str, int num = 1) {
while (num) {
cout << str << endl;
num--;
}
}
void test4() {
stringy beany;
char testing[] = "Reality isn't what is used to be.";
set(beany, testing);
show4(beany);
show4(beany, 2);
testing[0] = 'D';
testing[1] = 'u';
show4(testing);
show4(testing, 3);
show4("Done!");
}
// -------------------------------------------------test5
template <typename T>
T max5(T * array) {
T temp = array[0];
for (int i = 0; i < 5;i++) {
if (array[i] > temp) {
temp = array[i];
}
}
return temp;
}
void test5() {
int int_array[5] = { 1,2,3,4,5 };
double double_array[5] = { 1.2, 2.2, 33.2, 4.2 ,5.2 };
cout << "Max int: " << max5(int_array) << endl;
cout << "Max double: " << max5(double_array) << endl;
}
// -------------------------------------------------test6
template <typename T>
T maxn(T* array, int num) {
T temp = array[0];
for (int i = 0; i < num; i++) {
if (array[i] > temp) {
temp = array[i];
}
}
return temp;
}
template<> const char* maxn(const char* str[], int num) {
int max_length= strlen(str[0]);
int max_id = 0;
for (int i = 0; i < num;i++) {
if (strlen(str[i]) > max_length) {
max_length = strlen(str[i]);
max_id = i;
}
}
return str[max_id];
}
void test6() {
int int_array[6] = { 1,2,3,4,5,100 };
double double_array[4] = { 1.2, 2.2, 33.2, 4.2 };
cout << "Max int: " << maxn(int_array,6) << endl;
cout << "Max double: " << maxn(double_array,4) << endl;
const char* str[5] = { "apple","banana","orange_123","potato","watermelon" };
cout << "最长字符串:" << maxn(str, 5) << endl;
cout << "最长字符串地址:" << (void*)maxn(str, 5) << endl;
}
// -------------------------------------------------test7
template <typename T>
T SumArray(T arr[], int n)
{
T sum = T();
cout << "template A\n";
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
template <typename T>
T SumArray(T* arr[], int n)
{
cout << "template B\n";
decltype (*arr[0] + *arr[1]) sum= 0;
if (n > 0){
for (int i = 0; i < n; i++)
sum += *arr[i];
}
return sum;
}
struct debts
{
char name[50];
double amount;
};
void test7() {
int things[6] = { 13, 31, 103, 301, 310, 130 };
struct debts mr_E[3] =
{
{"Ima Wolfe", 2400.0},
{"Ura Foxe", 1300.0},
{"Iby Stout", 1800.0}
};
double* pd[3];
for (int i = 0; i < 3; i++)
pd[i] = &mr_E[i].amount;
cout << "Listing Mr. E's counts of things:\n";
cout << "Total of tings:" << SumArray(things, 6) << endl;
cout << "Listing Mr. E's debts:" << SumArray(pd, 3) << endl;
}
void main() {
//test1();
//test2();
//test3();
//test4();
//test5();
//test6();
test7();
}
1895

被折叠的 条评论
为什么被折叠?



