c++ primer plus 编程答案 上

c++ primer plus 编程答案上

第二章

  1. 编写一个c++程序,它显示您的姓名和地址
cpp 复制代码
#include<iostream>
int main() {
	using namespace std;
	cout << "my name is xxx,\nmy address is xxx" << endl;

	return 0;
}
  1. 编写一个c++程序,他要求用户输入一个以long为单位的距离,然后将她转化为为码。
cpp 复制代码
#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;
}
  1. 编写一个C++程序,它使用 3 个用户定义的函数(包括main()),并生成下面的输出:

    Three blind mice
    Three blind mice
    See how they run
    See how they run

其中一个函数要调用两次,该函数生成前两行;另一个函数也被调用两次,并生成其余的输出。

cpp 复制代码
#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;
}
  1. 编写一个程序,让用户输入其年龄,然后显示该年龄包含多少个月,如下所示:

    Enter your age: 29

cpp 复制代码
#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;
}
  1. 编写一个程序,其中的main( )调用一个用户定义的函数(以摄氏温度值为参数,并返回相应的华氏温度值)。该程序按下面的格式要 求用户输入摄氏温度值,并显示结果:

    Please enter a Celsius value: 20

    20 degrees Celsius is 68 degrees Fahrenheit.

转换公式:华氏温度 = 1.8×摄氏温度 + 32.0

cpp 复制代码
#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;
}
  1. 编写一个程序,其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天文单位.

cpp 复制代码
#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
cpp 复制代码
#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;
}

第三章

  1. 编写一个小程序,要求用户使用一个整数指出自己的身高(单位为英寸),然后将身高转换为英尺和英寸。该程序使用下划线字符来指示输入位置。另外,使用一个const符号常量来表示转换因子。
cpp 复制代码
#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---体重(千克)除以身高(米)的平方。用符号常量表示各种转 换因子。
cpp 复制代码
#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. 编写一个程序,要求用户以度、分、秒的方式输入一个纬度,然后以度为单位显示该纬度。1度为60分,1分等于60秒,请以符号常量的方式表示这些值。对于每个输入值,应使用一个独立的变量存储它。 下面是该程序运行时的情况:
cpp 复制代码
#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;
}
  1. 编写一个程序,要求用户以整数方式输入秒数(使用long或long long变量存储),然后以天、小时、分钟和秒的方式显示这段时间。使用符号常量来表示每天有多少小时、每小时有多少分钟以及每分钟有多 少秒。该程序的输出应与下面类似:

    Enter the number of seconds: 31600000
    31600000 seconds = 365 days, 17 hours, 46 minutes, 40 seconds.

cpp 复制代码
#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;
}
  1. 编写一个程序,要求用户输入全球当前的人口和中国当前的人口(或其他国家的人口)。将这些信息存储在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.

cpp 复制代码
#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;
}
  1. 编写一个程序,要求用户输入驱车里程(英里)和使用汽油量(加仑),然后指出汽车耗油量为一加仑的里程。如果愿意,也可以让程序要求用户以公里为单位输入距离,并以升为单位输入汽油量,然后 指出欧洲风格的结果---即每100公里的耗油量(升)。
cpp 复制代码
#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;
}
  1. 编写一个程序,要求用户按欧洲风格输入汽车的耗油量(每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。

cpp 复制代码
#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;
}
  1. 题: 修改程序清单4.4,使用 C++ string 类而不是 char 数组。
cpp 复制代码
#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;
}
  1. 编写一个程序,它要求用户首先输入其名,然后输入其姓;然后程序使用一个逗号和空格将姓和名组合起来,并存储和显示组合结果。请使用char数组和头文件cstring中的函数。下面是该程序运行时的 情形:

    Enter your first name: Flip
    Enter your last name: Fleming
    Here's the information in a single string: Fleming, Flip

cpp 复制代码
#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;
}
  1. 编写一个程序,它要求用户首先输入其名,再输入其姓;然后程序使用一个逗号和空格将姓和名组合起来,并存储和显示组合结果。请使用string对象和头文件string中的函数。下面是该程序运行时的情形:

    Enter your first name: Flip
    Enter your last name: Fleming
    Here's the information in a single string: Fleming, Flip

cpp 复制代码
#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 变量的内容。

cpp 复制代码
#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;
}
  1. 结构体 CandyBar 包含3个成员,如 编程练习5所示。请编写一个程序,创建一个包含 3 个元素的 CandyBar 数组,并将它们初始化为所选择的值,然后显示每个结构体的内容。
cpp 复制代码
#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;
}
  1. William Wingate从事比萨饼分析服务。对于每个披萨饼,他都需要记录下列信息:

披萨饼公司的名称,可以有多个单词组成;

披萨饼的直径;

披萨饼的重量。

请设计一个能够存储这些信息的结构体,并编写一个使用这种结构体变量的程序。程序将请求用户输入上述信息,然后显示这些信息。请使用 cin(或其它的方法)和cout。

cpp 复制代码
#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;
}
  1. 完成编程练习7,但使用 new 来为结构体分配内存,而不是声明一个结构体变量。另外,让程序在请求输入比萨饼公司名称之前输入比萨饼的直径。
cpp 复制代码
#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;
}
  1. 完成编程练习6,但使用 new 来动态分配数组,而不是声明一个包含 3 个元素的 CandyBar 数组。
cpp 复制代码
#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;
}
  1. 编写一个程序,让用户输入三次 40 码跑的成绩(如果您愿意,也可让用户输入40米跑的成绩),并显示次数和平均成绩。请使用一个 array对象来存储数据(如果编译器不支持 array 类,请使用数组)。
cpp 复制代码
#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;
}

第五章

  1. 编写一个要求用户输入两个整数的程序。该程序将计算并输出这两个整数之间(包括这两个整数)所有整数的和。这里假设先输入较小的整数。例如,用户输入的是2和9,则程序将指出2~9之间所有整数的和为44。
cpp 复制代码
#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;
}
  1. 使用 array 对象(而不是数组)和 long double(而不是 long long)重新编写程序清单5.4,并计算 100! 的值。
cpp 复制代码
#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;
}
  1. 编写一个要求用户输入数字的程序。每次输入后,程序都将报告到目前为止,所有输入的累计和。当用户输入 0 时,程序结束。
cpp 复制代码
#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的投资价值,并显示此时两个人的投资价值。

cpp 复制代码
#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数组中。然后,程序计算数组中各元素的总数,并报告这一年的销售情况。

cpp 复制代码
#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;
}
  1. 完成编程练习5,但这一次使用一个二维数组来存储输入------3年中每个月的销售量。程序将报告每年销售量以及三年的总销售量。
cpp 复制代码
#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

cpp 复制代码
#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;
}
  1. 编写一个程序,它使用一个 char数组和循环,每次读取一个单词,直到用户输入 done 为止。随后,该程序指出用户输入了多少个单词(不包括done在内)。下面是该程序的运行情况:

Enter words (type 'done' to stop): anteater birthday category dumpster

envy finagle genometry done for sure

You entered a total of 7 words.

您应在程序中包含头文件 cstring,并使用函数 strcmp() 来进行比较测试。

cpp 复制代码
#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,并使用关系运算符来进行 比较测试。

cpp 复制代码
#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;
}
  1. 编写一个使用嵌套循环的程序,要求用户输入一个值,指出要显示多少行。然后,程序将显示相应行数的星号,其中第一行包括一个星号,第二行包括两个星号,依此类推。每一行包含的字符数等于用户指定的行数,在星号不够的情况下,在星号前面加上句点。该程序的运 行情况如下:

Enter number of rows: 5 Output: ...* ...** ...*** .****

cpp 复制代码
#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;
}
相关推荐
秋の花1 分钟前
【JAVA基础】Java集合基础
java·开发语言·windows
香菜大丸2 分钟前
链表的归并排序
数据结构·算法·链表
jrrz08282 分钟前
LeetCode 热题100(七)【链表】(1)
数据结构·c++·算法·leetcode·链表
小松学前端4 分钟前
第六章 7.0 LinkList
java·开发语言·网络
可峰科技13 分钟前
斗破QT编程入门系列之二:认识Qt:编写一个HelloWorld程序(四星斗师)
开发语言·qt
oliveira-time14 分钟前
golang学习2
算法
咖啡里的茶i17 分钟前
Vehicle友元Date多态Sedan和Truck
c++
全栈开发圈17 分钟前
新书速览|Java网络爬虫精解与实践
java·开发语言·爬虫
面试鸭22 分钟前
离谱!买个人信息买到网安公司头上???
java·开发语言·职场和发展
小白学大数据22 分钟前
JavaScript重定向对网络爬虫的影响及处理
开发语言·javascript·数据库·爬虫