第二章
- 编写一个c++程序,它显示您的姓名和地址
#include<iostream>
int main() {
using namespace std;
cout << "my name is xxx,\nmy address is xxx" << endl;
return 0;
}
- 编写一个c++程序,他要求用户输入一个以long为单位的距离,然后将她转化为为码。
#include <iostream>
int main() {
using namespace std;
int distance = 0, yard;
cout << "Please input a distance numebr in the unit of Long: ";
cin >> distance;
yard = distance * 220;
cout << "The distance tranform in yards is: " << yard << endl;
return 0;
}
- 编写一个C++程序,它使用 3 个用户定义的函数(包括main()),并生成下面的输出:
Three blind mice
Three blind mice
See how they run
See how they run
其中一个函数要调用两次,该函数生成前两行;另一个函数也被调用两次,并生成其余的输出。
#include <iostream>
using namespace std;
void blind_mice() {
cout << "Three blind mice." << endl;
return;
}
void how_they_run() {
cout << "See how they run" << endl;
return;
}
int main() {
blind_mice();
blind_mice();
how_they_run();
how_they_run();
return 0;
}
- 编写一个程序,让用户输入其年龄,然后显示该年龄包含多少个月,如下所示:
Enter your age: 29
#include <iostream>
int main() {
using namespace std;
int years, months;
cout << "Enter your age: ";
cin >> years;
months = years * 12;
cout << years << " years is " << months << " monthes." << endl;
return 0;
}
- 编写一个程序,其中的main( )调用一个用户定义的函数(以摄氏温度值为参数,并返回相应的华氏温度值)。该程序按下面的格式要 求用户输入摄氏温度值,并显示结果:
Please enter a Celsius value: 20
20 degrees Celsius is 68 degrees Fahrenheit.
转换公式:华氏温度 = 1.8×摄氏温度 + 32.0
#include <iostream>
double celsiu2fahrenit(double celsius) {
return 1.8 * celsius + 32.0;
}
int main() {
using namespace std;
double celsius;
cout << "Please enter a celsius value: ";
cin >> celsius;
cout << celsius << " degrees Celsius is "
<< celsiu2fahrenit(celsius) << " degrees Fahrenheit." << endl;
return 0;
}
- 编写一个程序,其main( )调用一个用户定义的函数(以光年值为参数,并返回对应天文单位的值)。该程序按下面的格式要求用户输 入光年值,并显示结果:
Enter the number of light years: 4.2
4.2 light years = 265608 astromonical units.
天文单位是从地球到太阳的平均距离(约150000000公里或93000000英里),光年是光一年走的距离(约10万亿公里或6万亿英里)(除太阳外,最近的恒星大约离地球4.2光年)。请使用double类型,转换公式为:1光年=63240天文单位.
#include <iostream>
double light_years2astromonical_unit(double light_years) {
return light_years * 63240;
}
int main() {
using namespace std;
double light_years;
cout << "nter the number of light years: ";
cin >> light_years;
cout << light_years
<< " light years = "
<< light_years2astromonical_unit(light_years)
<< " astromonical units." << endl;
return 0;
}
7.编写一个程序,要求用户输入小时数和分钟数。在 main() 函数中,将这两个值传递给一个void函数,后者以下面这样的格式显示这两个值:
Enter the number of hours: 9
Enter the number of minutes: 28
Time: 9:28
#include <iostream>
using namespace std;
void display_time(double hours, double minutes) {
cout << "Time: " << hours << ":" << minutes << endl;
}
int main() {
double hours, minutes;
cout << "Enter the number of hours: ";
cin >> hours;
cout << "Enter the number of minutes: ";
cin >> minutes;
display_time(hours, minutes);
return 0;
}
第三章
- 编写一个小程序,要求用户使用一个整数指出自己的身高(单位为英寸),然后将身高转换为英尺和英寸。该程序使用下划线字符来指示输入位置。另外,使用一个const符号常量来表示转换因子。
#include <iostream>
const int Foot2inch = 12;
int main() {
using namespace std;
int input_height = 0;
cout << "Please input you height in inch: __\b\b";
cin >> input_height;
int height_foot = input_height / Foot2inch;
int height_inch = input_height % Foot2inch;
cout << "Your height in inch is: " << input_height
<< "; transforming in foot and inch is: "
<< height_foot << " foot "
<< height_inch << " inch." << endl;
return 0;
}
-
编写一个小程序,要求以几英尺几英寸的方式输入其身高,并以磅为单位输入其体重。(使用3个变量来存储这些信息。)该程序报告其BMI(Body Mass Index,体重指数)。为了计算BMI,该程序以英寸的方式指出用户的身高(1英尺为12英寸),并将以英寸为单位的身 高转换为以米为单位的身高(1英寸=0.0254米)。然后,将以磅为单位 的体重转换为以千克为单位的体重(1千克=2.2磅)。最后,计算相应的BMI—体重(千克)除以身高(米)的平方。用符号常量表示各种转 换因子。
#include <iostream>
const int Foot2Inch = 12;
const double Inch2Meter = 0.0254;
const double Kg2Pound = 2.2;
double BMI(double weight, double height) {
return weight/(height*height);
}
int main() {
using namespace std;
double height_foot = 0;
double height_inch = 0;
double weight_pound = 0;
cout << "Please enter your height in foot and Inch2Meter." << endl;
cout << "Enter the foot of height: __\b\b";
cin >> height_foot;
cout << "Enter the inch of height: __\b\b";
cin >> height_inch;
cout << "Please enter your weight in pound: __\b\b";
cin >> weight_pound;
double height_meter = (height_foot * Foot2Inch + height_inch) * Inch2Meter;
double weight_kg = weight_pound / Kg2Pound;
double bmi = BMI(weight_kg, height_meter);
cout << "Your BMI is: " << bmi << endl;
return 0;
}
- 编写一个程序,要求用户以度、分、秒的方式输入一个纬度,然后以度为单位显示该纬度。1度为60分,1分等于60秒,请以符号常量的方式表示这些值。对于每个输入值,应使用一个独立的变量存储它。 下面是该程序运行时的情况:
#include <iostream>
int main() {
using namespace std;
double degree, minutes, seconds;
cout << "Enter a latitude in degree, minutes and seconds." << endl;
cout << "First, enter the degree: ";
cin >> degree;
cout << "Next, enter the minutes of arc: ";
cin >> minutes;
cout << "Finally, enter the seconds of arc: ";
cin >> seconds;
double degree2 = degree + minutes/60 + seconds/3600;
cout << degree << " degrees, " << minutes << " minutes, "
<< seconds << " seconds = " << degree2 << endl;
return 0;
}
- 编写一个程序,要求用户以整数方式输入秒数(使用long或long long变量存储),然后以天、小时、分钟和秒的方式显示这段时间。使用符号常量来表示每天有多少小时、每小时有多少分钟以及每分钟有多 少秒。该程序的输出应与下面类似:
Enter the number of seconds: 31600000
31600000 seconds = 365 days, 17 hours, 46 minutes, 40 seconds.
#include <iostream>
int main() {
using namespace std;
long total_seconds;
cout << "Enter the number of seconds: ";
cin >> total_seconds;
int days = total_seconds / 86400;
int hours = (total_seconds % 86400) / 3600;
int minutes = ((total_seconds % 86400) % 3600) / 60;
int seconds = ((total_seconds % 86400) % 3600) % 60;
cout << total_seconds << "seconds = "
<< days << " days, "
<< hours << " hours, "
<< minutes << " minutes, "
<< seconds << " seconds." << endl;
return 0;
}
- 编写一个程序,要求用户输入全球当前的人口和中国当前的人口(或其他国家的人口)。将这些信息存储在long long变量中,并让程序显示中国(或其他国家)的人口占全球人口的百分比。该程序的输出 应与下面类似:
Enter the world's population: 7850176700
Enther the population of China: 1411780000
The population of the China is 17.9841% of the world population.
#include <iostream>
int main() {
using namespace std;
long long population_world, population_China;
cout << "Enter the world's population: ";
cin >> population_world;
cout << "Enter the population of China: ";
cin >> population_China;
double rate = double(population_China)/population_world;
cout << "The population of the China is " << rate * 100
<< "% of the world population." << endl;
return 0;
}
- 编写一个程序,要求用户输入驱车里程(英里)和使用汽油量(加仑),然后指出汽车耗油量为一加仑的里程。如果愿意,也可以让程序要求用户以公里为单位输入距离,并以升为单位输入汽油量,然后 指出欧洲风格的结果—即每100公里的耗油量(升)。
#include <iostream>
int main() {
using namespace std;
double kilometer, oil_liter;
cout << "Enter the distance that you've dirver in kilometer: ";
cin >> kilometer;
cout << "Enter the comsumption of oil: ";
cin >> oil_liter;
double kilometer_per_liter = kilometer / oil_liter;
cout << "The average fuel comsumption is "
<< 100 / kilometer_per_liter << " L/100km" << endl;
}
- 编写一个程序,要求用户按欧洲风格输入汽车的耗油量(每100公里消耗的汽油量(升)),然后将其转换为美国风格的耗油量—每加仑多少英里。
注意,除了使用不同的单位计量外,美国方法(距离/燃
料)与欧洲方法(燃料/距离)相反。100公里等于62.14英里,1加仑等于3.875升。因此,19mpg大约合12.4l/100km,27mpg大约合
8.71/100km。
#include <iostream>
int main() {
using namespace std;
const double Km2Mile = 0.6214;
const double Gallon2Litre = 3.875;
double fuel_comsuption_en = 0.0;
cout << "Enter the fuel comsuption in European standard: ";
cin >> fuel_comsuption_en;
double fuel_comsuption_us = (100 * Km2Mile) / (fuel_comsuption_en/Gallon2Litre);
cout << "The fuel comsuption in US standard is " << fuel_comsuption_us
<< " Miles/Gallon (mpg)." << endl;
return 0;
}
第四章
题: 编写一个程序,如下输出实例所示的请求并显示信息:
What is your first name? Betty Sue
Waht is your last name? Yewe
What letter grade do you deserve? B
What is your age? 22
Name: Yewe, Betty Sue
Grade: C
Age: 22
程序应接受的名字包含多个单词。另外,程序将向下调整成绩。假设用户请求A、B或C,返回 B、C 或 D。
#include<iostream>
#include<string>
int main() {
using namespace std;
char first_name[40];
char last_name[40];
char grade_letter;
int age;
cout << "What is your first name: ";
cin.getline(first_name, 40);
cout << "What is your last name: ";
cin.getline(last_name, 40);
cout << "What letter grade do you deserve: ";
cin >> grade_letter;
cout << "What is your age: ";
cin >> age;
cout << "Name: " << last_name << ", " << first_name << endl;
cout << "Grade: " << char(grade_letter + 1) << endl;
cout << "Age:" << age << endl;
return 0;
}
- 题: 修改程序清单4.4,使用 C++ string 类而不是 char 数组。
#include<iostream>
#include<string>
int main() {
using namespace std;
string name;
string dessert;
cout << "Enter your name:" << endl;
getline(cin, name);
cout << "Enter your favorite dessert" << endl;
getline(cin, dessert);
cout << "I have delicious " << dessert;
cout << " for you, " << name << "." << endl;
return 0;
}
- 编写一个程序,它要求用户首先输入其名,然后输入其姓;然后程序使用一个逗号和空格将姓和名组合起来,并存储和显示组合结果。请使用char数组和头文件cstring中的函数。下面是该程序运行时的 情形:
Enter your first name: Flip
Enter your last name: Fleming
Here's the information in a single string: Fleming, Flip
#include<iostream>
#include<string>
#include<cstring>
int main() {
using namespace std;
char first_name[20], last_name[20];
char final_name[50];
cout << "Enter your last_name:";
cin.getline(last_name, 20);
cout << "Enter your first_name:";
cin.getline(first_name, 20);
strcpy(final_name, last_name);
strcat(final_name, ",");
strcat(final_name, first_name);
cout << "Here's the information in a single string: " << final_name << endl;
return 0;
}
- 编写一个程序,它要求用户首先输入其名,再输入其姓;然后程序使用一个逗号和空格将姓和名组合起来,并存储和显示组合结果。请使用string对象和头文件string中的函数。下面是该程序运行时的情形:
Enter your first name: Flip
Enter your last name: Fleming
Here's the information in a single string: Fleming, Flip
#include<iostream>
#include<string>
int main() {
using namespace std;
string first_name, last_name;
string final_name;
cout << "Enter your first name" << endl;
getline(cin, first_name);
cout << "Enter your last name" << endl;
getline(cin, last_name);
final_name = last_name + "," + first_name;
cout << "Here's the information in a single string: " << final_name << endl;
return 0;
}
结构体 CandyBar 包含3个成员。第一个成员存储了糖块的品牌;第二个成员存储糖块的重量(可以有小数);第三个成员存储了糖块的卡路里含量(整数)。编写一个程序,声明这个结构体,创建一个名为 snack 的 CandyBar 变量,并将其成员分别初始化为 “Mocha Munch”、2.3 和 350。初始化应在声明 snack 时进行。最后,程序显示 snack 变量的内容。
#include <iostream>
#include <string>
struct CandyBar
{
std::string name;
double weight;
int calories;
};
int main() {
using namespace std;
CandyBar snack = { "Mocha Munch", 2.3, 350 }; // 初始化结构体
cout << "The name of the CandyBar: " << snack.name << endl;
cout << "The weight of the candy: " << snack.weight << endl;
cout << "The calories information: " << snack.calories << endl;
return 0;
}
- 结构体 CandyBar 包含3个成员,如 编程练习5所示。请编写一个程序,创建一个包含 3 个元素的 CandyBar 数组,并将它们初始化为所选择的值,然后显示每个结构体的内容。
#include <iostream>
#include <string>
struct CandyBar
{
std::string name;
double weight;
int calories;
};
int main() {
using namespace std;
CandyBar candbar[3] = {
{"Mocha Munch", 2.3, 350},
{"Big Rabbit", 5, 300},
{"Joy Boy", 4.1, 430}
};
cout << "The name of the CandyBar: " << candbar[0].name << endl;
<< "The weight of the candy: " << candbar[0].weight << endl;
<< "The calories information: " << candbar[0].calories << endl<<endl;
cout << "The name of the CandyBar: " << candbar[1].name << endl;
<< "The weight of the candy: " << candbar[1].weight << endl;
<< "The calories information: " << candbar[1].calories << endl<<endl;
cout << "The name of the CandyBar: " << candbar[2].name << endl;
<< "The weight of the candy: " << candbar[2].weight << endl;
<< "The calories information: " << candbar[2].calories << endl;
return 0;
}
- William Wingate从事比萨饼分析服务。对于每个披萨饼,他都需要记录下列信息:
披萨饼公司的名称,可以有多个单词组成;
披萨饼的直径;
披萨饼的重量。
请设计一个能够存储这些信息的结构体,并编写一个使用这种结构体变量的程序。程序将请求用户输入上述信息,然后显示这些信息。请使用 cin(或其它的方法)和cout。
#include <iostream>
#include <string>
struct Pizza
{
std::string company;
double diameter;
double weight;
};
int main() {
using namespace std;
Pizza pizza;
cout << "Enter the pizza company: ";
getline(cin, pizza.company);
cout << "Enter the diameter of pizza: ";
cin >> pizza.diameter;
cout << "Enter the weight of pizza: ";
cin >> pizza.weight;
cout << "\nHere is the pizza information: "<<endl
<< "Company: " << pizza.company << endl
<< "Diameter: " << pizza.diameter << endl
<< "Weight: " << pizza.weight << endl;
return 0;
}
- 完成编程练习7,但使用 new 来为结构体分配内存,而不是声明一个结构体变量。另外,让程序在请求输入比萨饼公司名称之前输入比萨饼的直径。
#include <iostream>
#include <string>
struct Pizza
{
std::string company;
double diameter;
double weight;
};
int main() {
using namespace std;
Pizza* pizza = new Pizza;
cout << "Enter the diameter of pizza: ";
cin >> pizza->diameter;
cout << "Enter the weight of pizza: ";
cin >> pizza->weight;
cin.get();
cout << "Enter the pizza company: ";
getline(cin, pizza->company);
cout << endl<<"Here is the pizza information: "<<endl
<< "Company: " << pizza->company << endl
<< "Diameter: " << pizza->diameter << endl
<< "Weight: " << pizza->weight << endl;
delete pizza;
return 0;
}
- 完成编程练习6,但使用 new 来动态分配数组,而不是声明一个包含 3 个元素的 CandyBar 数组。
#include <iostream>
#include <string>
struct CandyBar
{
std::string name;
double weight;
int calories;
};
int main() {
using namespace std;
CandyBar *p_candybar = new CandyBar [3] {
{"Mocha Munch", 2.3, 350},
{"Big Rabbit", 5, 300},
{"Joy Boy", 4.1, 430}
};
// 输出第一个结构体元素,按照数组的方式输出
cout << "The name of the CandyBar: " << p_candybar[0].name << endl
<< "The weight of the candy: " << p_candybar[0].weight << endl
<< "The calories information: " << p_candybar[0].calories << endl<<endl;
// 输出第二个结构体元素,可以按照指针的逻辑输出
cout << "The name of the CandyBar: " << (p_candybar+1)->name << endl
<< "The weight of the candy: " << (p_candybar+1)->weight << endl
<< "The calories information: " << (p_candybar+1)->calories << endl<<endl;
// 输出第三个结构体元素,又是数据的方式
cout << "The name of the CandyBar: " << p_candybar[2].name << endl
<< "The weight of the candy: " << p_candybar[2].weight << endl
<< "The calories information: " << p_candybar[2].calories << endl;
delete [] p_candybar;
return 0;
}
- 编写一个程序,让用户输入三次 40 码跑的成绩(如果您愿意,也可让用户输入40米跑的成绩),并显示次数和平均成绩。请使用一个 array对象来存储数据(如果编译器不支持 array 类,请使用数组)。
#include <iostream>
#include <array>
int main() {
using namespace std;
array<double, 3> result;
cout << "Enter threed result of the 40 meters runing time: \n";
cin >> result[0];
cin >> result[1];
cin >> result[2];
double ave_result = (result[0] + result[1] + result[2]) / 3;
cout << "The all three time results are: " << result[0] << ", "
<< result[1] << ", " << result[2] << endl;
cout << "The average result: " << ave_result << endl;
return 0;
}
第五章
- 编写一个要求用户输入两个整数的程序。该程序将计算并输出这两个整数之间(包括这两个整数)所有整数的和。这里假设先输入较小的整数。例如,用户输入的是2和9,则程序将指出2~9之间所有整数的和为44。
#include<iostream>
int main() {
using namespace std;
int number1, number2;
cout << "Enter the first number: ";
cin >> number1;
cout << "Enter the second number: ";
cin >> number2;
if (number1 > number2) {
int tmp;
tmp = number1;
number2 = number1;
number1 = tmp;
}
int s = 0;
for (int num = number1; num < number2 + 1; ++num)
s += num;
cout << "Sum the number from " << number1 << " to " << number2
<< ", sum = " << s << endl;
return 0;
}
- 使用 array 对象(而不是数组)和 long double(而不是 long long)重新编写程序清单5.4,并计算 100! 的值。
#include<iostream>
#include<array>
const int ar_size = 101;
int main() {
using namespace std;
array<long double, ar_size> factorials;
factorials[0] = factorials[1] = 1;
for (int i = 2; i < ar_size; ++i) {
factorials[i] = factorials[i - 1] * i;
}
for (int i = 0; i < ar_size ; ++i) {
cout << i << "! = " << factorials[i] << endl;
}
cout << endl;
return 0;
}
- 编写一个要求用户输入数字的程序。每次输入后,程序都将报告到目前为止,所有输入的累计和。当用户输入 0 时,程序结束。
#include<iostream>
int main() {
using namespace std;
double s =0 ;
double ch;
while (1) {
cout << "Enter a number (int/double) (0 to exit) : ";
cin >> ch;
if (ch == 0)
break;
s += ch;
cout << "Until now, the sum of the number you inputed is: "
<< s << endl;
}
return 0;
}
Daphne以10%的单利投资了100美元。也就是说,每一年的利润都是投资额的10%,即每年10美元。而Cleo以5%的复利投资了100美元。也就是说,利息是当前存款(包括获得的利息)的5%,Cleo在第一年投资100美元的盈利是5%—得到了105美元。下一年的盈利是105美元的5%—即5.25美元,依此类推。请编写一个程序,计算多少年后,Cleo的投资价值才能超过Daphne的投资价值,并显示此时两个人的投资价值。
#include <iostream>
int main() {
using namespace std;
double daphne_account = 100;
double cleo_account = 100;
int year = 0;
while (cleo_account <= daphne_account) {
++year;
daphne_account += 10;
cleo_account += cleo_account * 0.05;
}
cout << "After " << year << " Years. "
<< "Cleo's account is " << cleo_account
<< " while more than the one of Daphne which is "
<< daphne_account << "." << endl;
return 0;
}
假设要销售《C++ For Fools》一书。请编写一个程序,输入全年中每个月的销售量(图书数量,而不是销售额)。程序通过循环,使用初始化为月份字符串的 char * 数组(或 string 对象数组)逐月进行提示,并将输入的数据储存在一个int数组中。然后,程序计算数组中各元素的总数,并报告这一年的销售情况。
#include <iostream>
#include <string>
int main() {
using namespace std;
string months[12] = {"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
int sell[12];
int total_sales = 0;
cout << "Enter the sales of book <<C++ for Fools>> each month." << endl;
for (int i=0; i < 12; ++i) {
cout << months[i] << ":";
cin >> sell[i];
total_sales += sell[i];
}
cout << "\nThe total sales is " << total_sales << endl;
for (int i=0; i < 12; ++i) {
cout << months[i] << ": " << sell[i] << endl;
}
return 0;
}
- 完成编程练习5,但这一次使用一个二维数组来存储输入——3年中每个月的销售量。程序将报告每年销售量以及三年的总销售量。
#include <iostream>
#include <string>
int main() {
using namespace std;
string months[12] = {"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
int sells[3][12];
int total_sales[3] = {0, 0, 0};
for (int i=0; i<3; ++i) {
cout << "Enter " << i+1 << " year(s) sales of book <<C++ for Fools>> each month." << endl;
for (int j=0; j<12; ++j) {
cout << months[j] << ": ";
cin >> sells[i][j];
total_sales[i] += sells[i][j];
}
}
for (int i=0; i<3; ++i) {
cout << i+1 << " year(s) total sales is "
<< total_sales[i] << endl;
}
cout << "There years total sales is "
<< total_sales[0] + total_sales[1] + total_sales[2] << endl;
return 0;
}
设计一个名为 car 的结构体,用它存储下述有关汽车的信息:生产商(存储在字符数组或 string 对象中的字符串)、生产年份(整数)。编写一个程序,向用户询问有多少辆汽车。随后,程序使用new来创建一个由相应数量的 car 结构体组成的动态数组。接下来,程序提示用户输入每辆车的生产商(可能由多个单词组成)和年份信息。请注意,这需要特别小心,因为它将交替读取数值和字符串(参见第4章)。最后,程序将显示每个结构的内容。该程序的运行情况如下:
How many cars do you wish to catalog? 2 Car #1: Please enter the
maker: Hudson Hornet Please enter the year made: 1952 Car #2: Please
enter the maker: Kaiser Please enter the year made: 1951 Here is your
collection: 1952 Hudson Hornet 1951 Kaiser
#include <iostream>
#include <string>
int main() {
using namespace std;
struct Car {
string company;
int year;
};
int car_num = 0;
cout << "How many cars do you wish to catalog? ";
cin >> car_num;
cin.get() // 读取输入流末尾的回车
Car *cars = new Car[car_num];
for (int i=0; i < car_num; ++i) {
cout << "Please enter the maker: ";
cin >> (cars+i)->company;
cout << "Please enter the year made: ";
cin >> (cars+i)->year;
}
cout << "\nHere is your collection: \n";
for (int i=0; i < car_num; ++i) {
cout << cars[i].year << " " << cars[i].company << endl;
}
delete [] cars;
return 0;
}
- 编写一个程序,它使用一个 char数组和循环,每次读取一个单词,直到用户输入 done 为止。随后,该程序指出用户输入了多少个单词(不包括done在内)。下面是该程序的运行情况:
Enter words (type ‘done’ to stop): anteater birthday category dumpster
envy finagle genometry done for sureYou entered a total of 7 words.
您应在程序中包含头文件 cstring,并使用函数 strcmp() 来进行比较测试。
#include <iostream>
#include <cstring>
int main() {
using namespace std;
int word_count = 0;
char ch[80];
cout << "Enter a word (type 'done' to stop the program.): \n";
do {
cin >> ch;
if (strcmp(ch, "done") != 0) {
word_count++;
}
} while (strcmp(ch, "done") != 0);
cout << "\nYou entered a total of " << word_count << " words." << endl;
return 0;
}
编写一个满足前一个练习中描述的程序,但使用 string 对象而不是字符数组。请在程序中包含头文件 string,并使用关系运算符来进行 比较测试。
#include <iostream>
#include <string>
int main() {
using namespace std;
int word_count = 0;
string ch;
cout << "Enter a word (type 'done' to stop the program.): \n";
do {
cin >> ch;
if (ch != "done") {
word_count++;
}
} while (ch != "done");
cout << "\nYou entered a total of " << word_count << " words." << endl;
return 0;
}
- 编写一个使用嵌套循环的程序,要求用户输入一个值,指出要显示多少行。然后,程序将显示相应行数的星号,其中第一行包括一个星号,第二行包括两个星号,依此类推。每一行包含的字符数等于用户指定的行数,在星号不够的情况下,在星号前面加上句点。该程序的运 行情况如下:
Enter number of rows: 5 Output: …* …** …*** .****
#include <iostream>
int main() {
using namespace std;
int line_num = 0;
cout << "Enter the number of rows: ";
cin >> line_num;
cout << "Output:" << endl;
for (int i = line_num; i > 0; --i) {
for (int j = i-1; j > 0; --j) {
cout << ".";
}
for (int j = line_num - (i-1); j > 0; --j) {
cout << "*";
}
cout << "\n";
}
return 0;
}
第六章
- 编写一个程序,读取键盘输入,直到遇到 @符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大 写(别忘了cctype函数系列)。
#include <iostream>
#include <cctype>
int main() {
using namespace std;
char ch;
cout << "Enter any charater: ";
while ((ch=cin.get()) != '@') {
if (isdigit(ch)) {
continue;
} else if (islower(ch)) {
ch = toupper(ch);
} else if (isupper(ch)) {
ch = tolower(ch);
}
cout << ch;
}
cout << endl<<"That's all!" << endl;
return 0;
}
- 编写一个程序,最多将10个 donation 值读入到一个 double 数组中(如果您愿意,也可使用模板类 array )。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
#include <iostream>
#include <array>
int main() {
using namespace std;
const unsigned int size = 10;
array<double, size> donation;
double sum_value = 0;
unsigned int large_avg = 0, n = 0;
cout << "Enter 10 double value or type non-digital value to exit: ";
while ((n < size) && (cin >> donation[n])) {
sum_value += donation[n];
++n;
}
double avg = sum_value / n;
for (int i=0; i < n; i++) {
if (donation[i]>avg)
++large_avg;
}
cout << "The average value is: " << avg
<< ", there are " << large_avg
<< " larger than average value." << endl;
return 0;
}
编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。如果用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条 switch 语句,根据用户的选择执行一个简单操作。该程序的运行情况如下:
Please enter one of the following choices:
c) carnivore p) pianist
t) tree g) game
f
Please enter a c, p, t, or g: q
A maple is a tree.
#include <iostream>
int main() {
using namespace std;
cout << "Please enter one of the following choice: \n";
cout << "c) carnivore\tp) pianist.\n"
<< "t) tree\tg) game" << endl;
bool exit = false;
char c;
while (!exit && (cin >> c)) {
switch (c) {
case 'c':
cout << "Tiger is a carnivore." << endl;
exit = true;
break;
case 'p':
cout << "Mozart is a great pianst." << endl;
exit = true;
break;
case 't':
cout << "A maple is a tree." << endl;
exit = true;
break;
case 'g':
cout << "Supper Mario is a great game." << endl;
exit = true;
break;
default:
cout << "Please enter c, p, t, or g: q" << endl;
break;
}
}
return 0;
}
加入 Benevolent Order of Programmer 后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名来了解他(她)。请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序时,请使用下面的结构:
// Benevolent order of programmers strcture
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
};
该程序创建一个有上述结构体组成的小型数组,并将其初始化为适当的值。另外,该程序使用一个循环,让用户在下面的选项中进行选择:
a. display by name b. display by title
c. display by bopname d. display by preference
q. quit
注意,display by preference
并不意味着显示成员的偏好,而是意味着根据成员的偏好来列出成员。例如,如果偏好号为 1,则选择 d 将显示成员的头衔。该程序的运行情况如下:
Benevolent order of Programmers report.
a. display by name b. display by title
c. display by bopname d. display by preference
q. quit
Enter your choices: a
Wimp Macho
Raki Rhodes
Celia Laiter
Hoppy Hipman
Pat Hand
Next choice: d
Wimp Macho
Junior Programmer
MIPS
Analyst Trainee
LOOPY
Next choice: q
Bye!
#include <iostream>
using namespace std;
const int strsize = 50;
struct bop {
char fname[strsize];
char title[strsize];
char bopname[strsize];
int pre;
};
int main() {
bop info[5] = {
{"Wimp Macho", "W", "Wimp", 0},
{"Raki Rhodes", "R", "Raki", 1},
{"Celia Laiter", "C", "Celia", 2},
{"Hoppy Hipman", "H", "Hoppy", 0},
{"Pat Hand", "P", "Pat", 1} };
char choice;
cout << "benevolent order of progeammers report\n"
<< "a)display by name b)display by title\n"
<< "c)display by bopname d)display by preference\n"
<< "q)quit\n";
cout << "enter ur choice:";
cin >> choice;
while (choice != 'q') {
switch (choice) {
case 'a':
for (int i = 0; i < 5; i++)
cout << info[i].fname << endl;
break;
case 'b':
for (int i = 0; i < 5; i++)
cout << info[i].title << endl;
break;
case 'c':
for (int i = 0; i < 5; i++)
cout << info[i].bopname << endl;
break;
case 'd': {
for (int i = 0; i < 5; i++) {
switch (info[i].pre) {
case 0:
cout << info[i].fname << endl;
break;
case 1:
cout << info[i].title << endl;
break;
case 2:
cout << info[i].bopname << endl;
break;
}
}
}break;
}
cout << "next choice:\n";
cin >> choice;
}
cout << "Bye!";
return 0;
}
在 Neutronia 王国,货币单位是 tvarp,收入所得税的计算方式如下:
- 5000 tvarps:不收税;
- 5001~15000 tvarps:10%;
- 15001~35000 tvarps:15%;
- 35000 tvarps以上:20%;
例如,收入为 38000 tvarps 时,所得税为 5000 * 0.00 + 10000 * 0.10 + 20000 * 0.15 + 3000 * 0.20, 即 4600 tvarps。请编写一个程序,使用循环来 要求用户输入收入,并报告所得税。当用户输入负数或非数字时,循环将结束。
#include <iostream>
int main() {
using namespace std;
const double tax_rate1 = 0.1;
const double tax_rate2 = 0.15;
const double tax_rate3 = 0.20;
double income = 0.0, tax = 0.0;
cout << "Please enter your income: ";
while ((cin >> income) && (income > 0)) {
if (income <= 5000) {
tax = 0.0;
} else if (income <= 15000 ) {
tax = (income - 5000) * tax_rate1;
} else if (income <= 35000) {
tax = (15000 - 5000) * tax_rate1 + (income - 15000) * tax_rate2;
} else {
tax = (15000 - 5000) * tax_rate1 + (35000 - 15000) * tax_rate2 + (income - 35000) * tax_rate3;
}
cout << "Income = " << income << ", tax = " << tax << endl;
cout << "Please enter your income again or enter a negative value to quit: ";
}
return 0;
}
编写一个程序,记录捐助给 “维护合法权利团体” 的资金。该程序要求用户输入捐献者数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被储存在一个动态分配的结构体数组中。每个结构体有两个成员:用来储存姓名的字符数组(或 string对象)和用来存储款项的 double成员。读取所有的数据后,程序将显示所有捐款超过 10000 的捐款者的姓名及其捐款数额。
该列表前应包含一个标题,指出下面的捐款者是重要捐款人 Grand Patrons。然后,程序将列出其他的捐款者,该列表要以 Patrons 开头。如果某种类别没有捐款者,则程序将打印单词 none。该程序只显示这两种类别,而不进行排序。
#include <iostream>
#include <string>
int main() {
using namespace std;
const int Grand_Amount = 10000;
struct Patron {
string name;
double amount;
};
int contribute_num = 0;
cout << "Enter the number of contributor: ";
cin >> contribute_num;
cin.get(); // 读取输入流中的回车符
Patron *p_contribution = new Patron [contribute_num];
for (int i = 0; i < contribute_num; ++i) {
cout << "Enter the name of " << i + 1 << " contributor: ";
getline(cin, p_contribution[i].name);
cout << "Enter the amount of donation: ";
cin >> p_contribution[i].amount;
cin.get(); // 读取输入流中的回车符
}
unsigned int grand_amount_n = 0;
cout << "\nGrand patron: " << endl;
for (int i = 0; i < contribute_num; ++i) {
if (p_contribution[i].amount > Grand_Amount) {
cout << "Contributor name: " << p_contribution[i].name << "\n"
<< "Contributor amount: " << p_contribution[i].amount << endl;
++grand_amount_n;
}
}
if (grand_amount_n == 0) {
cout << "None" << endl;
}
bool is_empty = true;
cout << "\nPatrons: " << endl;
for (int i=0; i < contribute_num; ++i) {
cout << "Contributor name: " << p_contribution[i].name << "\n"
<< "Contributor amount: " << p_contribution[i].amount << endl;
is_empty = false;
}
if (is_empty) {
cout << "** None **" << endl;
}
return 0;
}
编写一个程序,它每次读取一个单词,直到用户输入 q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。为此,方法之一是,使用 isalpha() 来区分以字母和其他字符打头的单词,然后对于通过了 isalpha() 测试的单词,使用 if 或 switch 语句来确定哪些以元音打头。
该程序的运行情况如下:
Enter words (q to quit):
The 12 awesome oxen ambled
quietly across 15 meters of lawn. q
5 words beginning with vowels
4 words beginning with consonants
2 others
#include <iostream>
#include <cctype>
#include <string>
int main() {
using namespace std;
unsigned int vowels = 0;
unsigned int consonants = 0;
unsigned int other = 0;
string input;
cout << "Enter words (q to quit): " << endl;
while (cin >> input) {
if (input == "q")
break;
if (isalpha(input[0])) {
switch(toupper(input[0])) {
case 'A':;
case 'E':;
case 'I':;
case 'O':;
case 'U':
++vowels;
break;
default:
++consonants;
break;
}
} else {
++other;
}
}
cout << vowels << " words beginning with vowels.\n"
<< consonants << " words beginning with consonants.\n"
<< other << " words beginning with other letter." << endl;
return 0;
}
编写一个程序,它打开一个文件文件,逐个字符地读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符。
#include <iostream>
#include <fstream>
#include <string>
int main() {
using namespace std;
string fn;
ifstream in_file_handle;
unsigned int n = 0;
char ch;
cout << "Enter a file name: ";
getline(cin, fn);
in_file_handle.open(fn.c_str());
while ((ch = in_file_handle.get()) != EOF) {
++n;
}
in_file_handle.close();
cout << "There are " << n << " characters in "
<< fn << " file." << endl;
return 0;
}
- 完成编程练习6,但从文件中读取所需的信息。该文件的第一项 应为捐款人数,余下的内容应为成对的行。在每一对中,第一行为捐款人姓名,第二行为捐款数额。即该文件类似于下面:
4 Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000
#include <iostream>
#include <fstream>
#include <string>
int main() {
using namespace std;
const int Grand_Amount = 10000;
string file_name;
ifstream in_file_handle;
struct Patron {
string name;
double amount;
};
int contribute_num = 0;
cout << "Enter a file name: ";
getline(cin, file_name);
in_file_handle.open(file_name.c_str());
in_file_handle >> contribute_num;
in_file_handle.get(); // 读取空白
Patron *p_contribution = new Patron [contribute_num];
for (int i = 0; i < contribute_num; ++i) {
/*
* 4 Sam Stone
* 2000
* Freida Flass
* 100500
* Tammy Tubbs
* 5000
* Rich Raptor
* 55000
*
*/
getline(in_file_handle, p_contribution[i].name);
in_file_handle >> p_contribution[i].amount;
in_file_handle.get(); // 读掉空白(包括滞留在行末的回车符)
}
in_file_handle.close();
unsigned int grand_amount_n = 0;
cout << "\nGrand patron: " << endl;
for (int i = 0; i < contribute_num; ++i) {
if (p_contribution[i].amount > Grand_Amount) {
cout << "Contributor name: " << p_contribution[i].name << "\n"
<< "Contributor amount: " << p_contribution[i].amount << endl;
++grand_amount_n;
}
}
if (grand_amount_n == 0) {
cout << "None" << endl;
}
bool is_empty = true;
cout << "\nPatrons: " << endl;
for (int i=0; i < contribute_num; ++i) {
cout << "Contributor name: " << p_contribution[i].name << "\n"
<< "Contributor amount: " << p_contribution[i].amount << endl;
is_empty = false;
}
if (is_empty) {
cout << "** None **" << endl;
}
delete [] p_contribution;
return 0;
}