1. 程式人生 > >c++ Primer Plus第5章課後習題程式碼

c++ Primer Plus第5章課後習題程式碼

#include <iostream>
#include <array>
#include <string>
#include <cstring>
using namespace std;

void test1() {
	int low, high;
	cin >> low >> high;
	cout << (low + high)*(high - low + 1) / 2 << endl;
}

void test2() {
	const int ArSize = 101;
	array<long double, ArSize> factorials;
	factorials[1] = factorials[0] = 1.0;
	for (int i = 2; i < ArSize; i++) {
		factorials[i] = i * factorials[i - 1];
	}
	
	cout << "100!= " << factorials[100] << endl;
}

void test3() {
	double num;
	double total = 0.0;
	while (cin >> num && num != 0) {
		total += num;
		cout <<"Total: "<< total << endl;
	}
}

void test4() {
	double daphne = 100.0;
	double cleo = 100.0;
	int cnt = 0;
	while (cleo <= daphne) {
		daphne += 10.0;
		cleo *= 1.05;
		cnt++;
	}
	cout << "After " << cnt << " years, cleo will earn more money than daphne" << endl;
	cout << "Cleo: " << cleo << ", Daphne: " << daphne << endl;
}

void test6() {
	const char * months[12] = {
		"Jan", "Feb", "Mar", "Apr", "May", "June", 
		"July", "Aug", "Sept", "Oct", "Nov", "Dec"
	};
	const int Years = 3;
	int sales[Years][12];
	int yearSale[Years];
	int totalSale = 0;
	for(int i=0; i<Years; i++){
		yearSale[i] = 0;
		for (int j = 0; j < 12; j++) {
			cout << "Enter sales of " << months[j] << ": ";
			cin >> sales[i][j];
			yearSale[i] += sales[i][j];
		}
		cout << "Year " << i << " sales: " << yearSale[i] << endl;
		totalSale += yearSale[i];
	}
	cout << "Total sales: " << totalSale << endl;
}

struct Car {
	std::string producer;
	int bornYear;
};
void test7() {
	int num;
	cout << "How many cars do you wish to catalog? ";
	cin >> num; cin.get();
	Car * carsPt = new Car[num];
	for (int i = 0; i < num; i++) {
		cout << "Car #" << i + 1 << ":\n";
		cout << "Please enter the make: ";
		getline(cin, carsPt[i].producer);
		cout << "Please enter the year made: ";
		cin >> carsPt[i].bornYear;
		cin.get();
	}

	cout << "Here is your collection:" << endl;
	for (int i = 0; i < num; i++) {
		cout << carsPt[i].bornYear << " " << carsPt[i].producer << endl;
	}
}

void test8() {
	char word[50];
	cout << "Enter words, (to stop, type the word done):" << endl;
	int cnt = 0;
	while (cin >> word) {
		cnt++;
		if (strcmp(word, "done") == 0) break;
	}
	cout << "You enter a total of " << cnt-1 << " words." << endl;
}

void test9() {
	string word;
	cout << "Enter words, (to stop, type the word done):" << endl;
	int cnt = 0;
	while (cin >> word) {
		cnt++;
		if ("done" == word) break;
	}
	cout << "You enter a total of " << cnt - 1 << " words." << endl;
}

void test10() {
	int rows;
	cout << "Enter number of rows: ";
	cin >> rows;
	cin.get();
	for (int i = 1; i <= rows; i++) {
		for (int j = rows - i; j >= 1; j--) {
			cout << ".";
		}
		for (int k = 1; k <= i; k++) {
			cout << "*";
		}
		cout << endl;
	}
}
int main() {
	test10();	
	system("pause");
	return 0;
}