C++ Primer plus(第六版)中文版

这篇博客介绍了C++编程的基础知识,包括程序的模块——函数,头文件的作用,名称空间的概念,以及C++中的输入输出操作。通过示例代码展示了如何使用iostream进行基本的输入输出,如读取整数和字符串,并解释了预编译头文件的作用。同时,还探讨了函数的声明和定义,包括返回值类型和参数类型。
摘要由CSDN通过智能技术生成

第二章练习

一、复习题

1.C++程序的模块叫什么
答:叫函数。
  为什么呢?
  由于函数创建C++程序的模块,对于C++的OOP至关重要。
  函数是一组一起执行一个任务的语句。每个 C++ 程序都至少有一个函数,即主函数 main() ,所有简单的程序都可以定义其他额外的函数。甚至也可以是一个函数,只要它完成一个功能,它就可以视为一个模块。
  而C++的模块一般是指一组函数的集合,来实现某一领域特定的功能。表现形式可以是封装在dll中的一组接口,也可以是在某个namespace下的一组API等等,主要是一个逻辑概念。
  这样看来,模块是指完成一个功能的函数集合,所以函数必不可少。
2.

        头文件的全部作用,就是把自己的所有内容直接“粘贴”到相应的 #include 语句处。正如文中答案上说的“这将导致在最终编译之前,使用 iostream 文件的内容替换该编译指令。”有关这部分的详细内容,请看c进行预处理、编译、连接、运行是做什么 - wujinzi_ujn的专栏 - 博客频道 - CSDN.NETC++预编译头文件 - 风生水起 - 博客频道 - CSDN.NET

3.所谓的名称空间其实就是指的标识符的各种可见范围,在C++标准程序库中标识符都被定义在一个名为STD的名称空间中。using namespace std是表示std中的标准库(类以及函数)引入到当前的作用域来,注意是可以直接的使用而不需要std::xxx的。

4.

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

5.6.

#include <iostream>

using namespace std;

int main()
{
   int cheeses;
   cheeses=32;
   cout<<cheeses<<endl;
}

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

int main()
{
   string cheeses;
   cout<<"请输入一串字符"<<endl;
   cin>>cheeses;
   cout<<cheeses<<endl;
}


//使用getline输入字符串

int main()
{


    string cheeses;
    cout<<"请输入一串字符串"<<endl ;
    getline(cin,cheeses,'a');
    cout<<cheeses;
   return 0;
}

//使用cin.get()输入字符串
int main()
{
    char str[20];
    cout<<"请输入一个字符串"<<endl;
    cin.get(str,20);
    cout<<str;
    return 0;

}

//使用cin.getline()输入字符串
int main()
{
    char str[20];
    cout<<"请输入一个字符串"<<endl;
    cin.getline(str,20);
    cout<<str;
    return 0;

}

8

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

int main()
{
   string cheeses;
   cout<<"请输入一串字符"<<endl;
   cin>>cheeses;
   cout<<"We have"<<cheeses<<" varieties of cheeses !";
}

9.

int froop(double t)                     void rattle (int n)                        int   prvoid(void)

函数名称为:froop                         函数名称:rattle                             函数名称:prvoid

返回值类型:int                              返回值类型:为空                         返回值类型:int

形参类型:double                          形参类型:int                                 形参类型:为空

10.返回类型为void时,不用在函数中使用return.

11.原因可能是没有加载iostream头文件,或者没有使用命名空间。

  • #include<iostream> ,加上using  std::cout;
  • #include<iostream> ,加上using namespace std;
  • #include<oostream>, 使用std::cout<<

二、编程练习

1.

#include <iostream>

using namespace std;

int main()
{
    cout << "我的姓名是:" << endl;
    cout<<"我的地址是:"<<endl;
    return 0;  
}

2.

#include <iostream>
using namespace std;

int main()
{
      int s;
    cout << "请输入一个以long为单位的距离(一long等于220码)" << endl;
    cin>>s;
    cout<<"转码后的地址是:"<<220*s<<endl;
    return 0;
}

3.

#include <iostream>
using namespace std;

void run1()
{
    cout <<"Three blind mice"<<endl;
}

void run2();

int main()
{
  run1();
  run1();
  run2();
  run2();
  return 0;
}

void run2()
{
    cout<<"See how they run"<<endl;
}

4.

#include <iostream>
using namespace std;

int main()
{
   const int x=12;
   int y;

   cout <<" 请输入你的年龄"<<endl;
   cin>>y;
   cout<<"你的年龄包含的月份有:"<<x*y<<endl;
   return 0;
}

5.

#include<iostream>
using namespace std;

double fun(double x)
{
    double y;
    y=1.8*x+32.0;
    return y;
}


int main()
{
    double x;
    cout <<"Please enter a Celsius value :"<<endl;
    cin>>x;
    cout<<x<<" degrees Celsius is "<<fun(x)<<" degrees Fahrenheit"<<endl;
}

6.

#include<iostream>
using namespace std;

double fun(double x)
{
    double y;
    y=63240*x;
    return y;
}


int main()
{
    double x;
    cout <<"Enter the number of light years :"<<endl;
    cin>>x;
    cout<<x<<" light years = "<<fun(x)<<" astronomical units."<<endl;
}

7.

#include<iostream>
using namespace std;

void fun(int x,int y)
{
cout<<"Time: "<<x<< ":" <<y<<endl;
}

int main()
{
  int x,y;
    cout<<"Enter the number of hours: "<<endl;
    cin>>x;
    cout<<"Enter the number of minutes: "<<endl;
    cin>>y;
    fun(x,y);
}

 第三章练习

一、复习题

1、整数有很多,如果将无限大的整数看作很大,则不可能用有限的计算机内存来表示所有的整数。因此,语言只能表示所有整数的一个子集。C++提供好几种整型,这样便能够根据程序的具体要求选择最合适的整型。

2、 a) short Value=80;

b) unsigned int Value=42110;

c) long long Value=3000000000; 或 unsigned long Value=3000000000;(建议使用这个)

3、C++本身并不能限制某个类型是否超出了它类型的范围,但是可以用 limits 头文件来看某种类型具体的范围。

4、33L和33这两个都是数值型常量。
  33L强制为长整数long型,33系统会识别为int整型。
  在数值上,两者相等,只是存储上,33根据编译器不同可能为2字节也可能为4字节,33L则一定为4字节。

5、这两条语句并不真正等价,虽然对于某些系统来说,它们是等效的。最重要的是,只有在使用ASCII码上的系统上,第一条语句是将ASCII编码值设置为字母A,而第二条语句还可用于使用其他编码的系统。其次,65是一个int常量,而'A'是一个char常量。

6、

char c = 88;
cout << c << endl;         // char type prints as character
cout.put(char{ 88 });       // put() prints char as character
cout << char{88} << endl;  // new-style type cast value to char
cout << (char)88 << endl;  // old-style type cast value to char

7.这种情况也还是得视系统而定,也就是说取决于两种类型的长度。如果 long 为 4 个字节,则没有损失,因为占 4 个字节的 long 的最大值为 2147483647,即有十位数,而 double 提供了至少十三位有效数字,这种情况下没有舍入误差。但是 long long 类型提供了 19 位数字,这超过了 double 的有效位数,故这种情况下有舍入误差。

8.a) 74, b) 4, c) 0, d) 4.5, e) 3。

9、

#include <iostream>
using namespace std;

int main()
{
	double x1, x2;
	int y;
	cin >> x1 >> x2;
	y = (int)( x1 + x2 );//或者使用y=int(x1+x2),但是编译器会报错
	cout << y << endl;
	return 0;
}

10

a.int

b.float

c.char

d.char32_t//auto crat = U'/U00002155' 字符常量中字符过多(编写时提示)

U再字符串前面代表 宽字符字符在串 即UNICODE 字符串。UTF-8/UTF-16 ...
等等
类型 char32_t 的宽字符文本,例如 U'a'

e.double

  •  后面的2.5如果后面不加f的话,就是个double类型的值
  •  /的两个操作数一个是float一个是double,float向double方向做类型提升(Type promotion)
  •  两个double的结果还是double,所以auto 的类型推断就认为fract是个double了

二、编程练习

1、

//一英尺等于12英寸,一英寸等于0.083英尺
#include<iostream>
using namespace std;

int main()
{
	 constexpr auto  F = 0.083;
	double high;
	
	cout << "请输入自己的身高" << endl;
	cin >> high;
	cout << "您的身高转化为英尺为" << endl;
	cout << F * high << endl;
	system("pause");
	return 0;
}

2、

#include<iostream>
using namespace std;

int main()
{       
	constexpr auto yczhm = 0.0254;
	constexpr auto yczhyc = 12;
	constexpr auto qgzhb = 0.0254;
	    int yhigh, chigh ,weight ;
		double zhigh, kweight,IBM;

		cout << "请以几英尺几英寸的方式输入你的身高" << endl;
	    cout << "你的身高有几英尺" << endl;
		cin >> yhigh;
		cout << "你的身高有几英寸" << endl;
		cin >> chigh;
		cout << "你的体重是多少磅" << endl;
		cin >> weight;
		zhigh = yczhm *(yczhyc * yhigh + chigh);
		kweight = weight * 1 / qgzhb;
		IBM = kweight / zhigh / zhigh;
		cout << "你的体重指数为:"<< IBM << endl;
		return 0;
}

3.

#include<iostream>
using namespace std;

int main()
{
	auto degrees = 0, minutes = 0, secends = 0;
	float final=0;
	constexpr int zh = 60;

	cout << "Enter a latitude in degree ,minutes,and seconds:" << endl;
	cout << "First,enter the degrees: " << endl;
	cin >> degrees;
	cout << "Next,enter the minutes of arc: " << endl;
	cin >> minutes;
	cout << "Finally,enter the secends of arc: " << endl;
	cin >> secends;
	final = degrees + minutes / zh + secends / zh / zh;
	cout << degrees << " degrees, " << minutes << " minutes, " << secends << " secends =  " << final << " degrees " << endl;
	return 0;
}

5.

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
 
	long long worldpopulation, USpopulation ;
	cout << "Enter the world's population : " << endl;
	cin >> worldpopulation;
	cout << "Enter the populartion of the US: " << endl;
	cin >> USpopulation;
	cout << "The population of the US is " <<  100 *( USpopulation*1.)/ (worldpopulation*1.) << "%" << endl;

	return 0;

}

6.

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
 
	int Facter, mileage1=0, quantity1=0, mileage2=0, quantity2=0;
	cout << "选择输入驱车里程和使用汽油量,选择以英里为单位输入距离键入:0,选择以公里为单位输入距离键入:1" << endl;
	cin >> Facter;
	if (Facter == 1)
	{   

		cout << "请输入驱车里程(英里): " << endl;
		cin >> mileage1;
		cout << "请输入使用汽油量(加仑): " << endl;
		cin >> quantity1;
		cout << "您的车耗油量为一加仑的里程: " << mileage1 / quantity1 << endl;
	}
	else
	{
		cout << "请输入驱车里程(公里): " << endl;
		cin >> mileage2;
		cout << "请输入使用汽油量(升): " << endl;
		cin >> quantity2;
		cout << "您的车每一百公里的耗油量为: " <<100* mileage2 / quantity2 << endl;
	}
	return 0;
}

7.

#include<iostream>
using namespace std;


int main()
{
	double x = 0;//输入的汽油量
	constexpr double y1 = 62.14, y2 = 3.875;
	cout << "按照欧洲风格输入汽车的耗油量(每一百公里消耗的汽油量)" << endl;
	cin >> x;
	cout <<  x/y1/y2;
}

第四章

 1.

char actor[30];
short betsic[100];
float chuck[13];
long double  dipsea[64];

2.

array<char, 30>actor;
array<short, 100>betsic;
array<float, 13>chuck;
array<long double, 64>dipsea;

3.

int arr[5] = { 1,3,5,7,9 };

4.

int even = arr[0] + arr[4];

5.

float ideas[6] = { 0,1,2,3,4,5 };
cout << ideas[2];

6.

char s[] = "cheeseburger";

7.

string s = "Waldorf Salad";

8.

struct Fish {
	string name;
	int weight;//单位为盎司
	float longs;//单位为小数
};

9.

int main()
{
	Fish fish;
	fish.name = "clownfish";
}

10.

enum Response{No,Yes,Maybe};

11.在使用vs编写程序时,有C26429的警告无法解决

#include<iostream> 
using namespace std;

int main()
{
	int ted = 2;
	int *p = &ted;
	cout << *p << endl;
}

12.

float treacle[10];
	float* p = treacle;
	cout << treacle[0] << treacle[10];

13.

	int x;
	cout << "请输入一个正整数" << endl;
	cin >> x;
	int* p = new int[x];	
	vector<int>Vec(x);

14.

cout << (int*)"Home of the jolly bytes";

有效,他将打印字符串的地址

15.

#include<iostream>
using namespace std;
#include<vector>

int main()
{

	struct Fish { char Kind[30]; int Weight; float Length; }; 
	Fish* p = new Fish; 
	cout << "Enter the kind of fish: " << endl; 
	cin >> p->Kind;
}

16.程序清单 4.6 的执行流程可以大致解释为:当输入 year 的值并按下回车键后, year 的值被存储在 year 中,但换行符被保留在了输入队列中,因此下面的 getline() 函数一眼便看到了换行符,于是便以为读到了行尾,因此便把一个空字符赋值给了address。所以使用 cin>>address 时,它可以使得程序跳过空白继续读取直到再次遇到空白字符位置。因此它可以跳过数字输入后保留下来的换行符,可以避免这个问题。但是又会引发另一个问题,也就是它只能读取一个单词,而不是一整行。

17.

#include<string> 
#include<vector>
 #include<array> 
const int Size=20; 
vector<string> VecStr(Size); 
array<string,Size> ArrStr;

4.13编程练习 

1.

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


int main()
{   
	string str1,str2,grade;
	int age;
	cout << "What is your first name?"<<endl;
	cin >> str1;
	cout << "What is your last name?"<<endl;
	cin >> str2;
	cout << "What letter grade do you deserve?"<<endl;
	cin >> grade;
	cout << "What is your age?"<<endl;
	cin >> age;
	cout << "Name:" << str2 << " , " << str1<<endl;
	cout << "Grade:"<<grade<< endl;
	cout << "Age: " << age << endl;
	
}

2.

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


int main()
{   
	const int ArSize = 20;
	string name, dessert;
	cout << "Enter your name:\n"<<endl;
	getline(cin, name);
	cout << "Enter your favorite dessert:\n"<<endl;
	getline(cin, dessert);
	cout << "I have some delicious " << dessert;
	cout << " for you, " << name << ",\n";
	return 0;
}

3.在vs中无法运行

#include<iostream> 
#include<stdlib.h>
#include<cstring>

using namespace std;

int main()
{
	char Name[2][20];
	cout << "Enter your first name: ";
	cin >> Name[0];
	cout << "Enter your second name: ";
	cin >> Name[1];
	cout << "Here is the information in a single string: " << strcat(strcat(Name[0], ", "), Name[1]) << endl;
	system("pause");
	return 0;
}

4.

#include<iostream> 
#include<string>

using namespace std;

int main()
{
	string firstName, secondName;
	cout << "Enter your first name: " << endl;
	cin >> firstName;
	cout << "Enter your second name: " << endl;
	cin >> secondName;
	cout << "Here's the information in a single string : " << firstName + "," + secondName<<endl;
}

5.

#include<iostream> 
#include<string>

using namespace std;
struct CandyBar {
	string name;
	float weight;
	int content;
};

int main()
{
	CandyBar snack = {
		"Mocha Munch",
		2.3,
		350,
	};

	cout << snack.name << endl;
	cout << snack.content << endl;
	cout << snack.weight << endl;
}

6.

#include<iostream> 
#include<string>

using namespace std;
struct CandyBar {
	string name;
	float weight;
	int content;
};

int main()
{

	CandyBar snack[3] = {
		{"Mocha Munch",2.3,350,},
		{"AAAA",4.5,450},
		{"BBBB",6.5,550},

	};
	cout << snack[0].name << endl;
	cout << snack[0].content << endl;
	cout << snack[0].weight << endl;

	cout << snack[1].name << endl;
	cout << snack[1].content << endl;
	cout << snack[1].weight << endl;

	cout << snack[2].name << endl;
	cout << snack[2].content << endl;
	cout << snack[2].weight << endl;
}

7.

#include<iostream> 
#include<string>

using namespace std;
struct Wingate {
	string name;
	int diameter;
	int height;
};

int main()
{
	Wingate campany;
	cout << "披萨饼公司的名称,可以有多个单词组成" << endl;
	cin >>campany.name;
	cout << "披萨饼的直径" << endl;
	cin >> campany.diameter;
	cout << "披萨饼的重量" << endl;
	cin >> campany.height;

	cout << "披萨饼公司的名称,可以有多个单词组成: " <<campany.name<< endl;
	cout << "披萨饼的直径: " <<campany.diameter<< endl;
	cout << "披萨饼的重量:"<<campany.height << endl;
}

 8.使用vs来编译时,是有警告的,提示需要使用智能模板库

#include<iostream> 
#include<string>

using namespace std;
struct Wingate {
	string name;
	int diameter;
	int height;
};

int main()
{
	Wingate *campany=new Wingate ;
	cout << "披萨饼公司的名称,可以有多个单词组成" << endl;
	cin >>campany->name;
	cout << "披萨饼的直径" << endl;
	cin >> campany->diameter;
	cout << "披萨饼的重量" << endl;
	cin >> campany->height;

	cout << "披萨饼公司的名称,可以有多个单词组成: " <<campany->name<< endl;
	cout << "披萨饼的直径: " <<campany->diameter<< endl;
	cout << "披萨饼的重量:"<<campany->height << endl;
	delete campany;
	return 0;
}

9.与上述8类似

10.

#include<iostream> 
#include<array>

using namespace std;


int main()
{
	float average;
	array<float, 3>grade;
	cout << "请输入第一次成绩" << endl;
	cin >> grade.at(0);
	cout << "请输入第二次成绩" << endl;
	cin >> grade.at(1);
	cout << "请输入第三次成绩" << endl;
	cin >> grade.at(2);
	average =(grade.at(0)+ grade.at(1)+ grade.at(2)) / 3;
	cout << "三次平均成绩是: " << average ;
}

【C++】C++11的std::array的详细剖析_Yngz_Miao的博客-CSDN博客_c++ std::array

第五章

 1、入口条件循环:程序进入循环体之前,先执行表达式的判断。若为真则开始执行循环体内的语句;若为假,则不执行循环体内的语句,越过循环体,执行循环体外的语句。
出口条件循环首先执行循环体内的语句,然后再判断表达式。若表达式为真,则再次执行循环体,若为假,则退出循环,执行循环之后的语句。

出口条件循环:do...while循环
入口条件循环:whlie循环、for循环

2、 

 3、

4、 5、

 6、

7、加大括号

8、表达式 int x=(1,024),这个表达式的右边由逗号运算符连接,因此 x 的值将被赋予 024,这是一个八进制形式,转换为十进制即为 20,也就是说 x 的值是20。而表达式 int y; y=1,024; 的意思是先将常量 1 赋给 y,而整个表达式的结果为 024,也就是 20,但结果并没有用而已。

9、cin>>ch 将跳过空白字符,比如换行符、空格以及制表符,而其它的两种形式都将读取这些字符。

二、编程练习

1、

#include<iostream>
using namespace std;

int main()
{
	int i, j,min,max;
	int sum=0;
	cout << "请输入两个整数" << endl;
	cin >> i >> j;
	if(i>j)
	{
		max = i;
		min = j;
	}
	else
	{
		max = j;
		min = i;
	}
	while (min <= max)
	{
		sum += min;
		min++;
	}
	cout << "两数之间的整数和为: " << sum << endl;	
}

2、

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

int main()
{
	constexpr int ArSize = 100;
	array <long double, 100>factor;
	factor.at(1) = factor.at(0)= 1;
	for (int i = 2; i < ArSize; i++)
		factor.at(i) = i * factor.at(i-1);
	for (int i = 0; i < ArSize; i++)
		cout << i << " != " << factor.at(i) << endl;
}

3、

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

int main()
{
	int i;
	int sum = 0;
	cout << "请输入一个非零要加的数字" << endl;
	cin >> i;
	while (i!= 0)
	{
		sum += i;
		cout << "请输入一个要加的数字(若输入零则程序停止)" << endl;
		cin >> i;
	}
	cout << "所有数字累加和为: " << sum << endl;	
}

4、

#include<iostream>
using namespace std;

int main()
{
	double 	Dinterest =100, Cinterest =100;
	int i = 0;
	while (Dinterest>=Cinterest)
	{
		i++;
		Dinterest = 0.1 * 100 * i + 100;
		Cinterest = 0.05 * Cinterest+Cinterest;	
	}
	cout << "第 " << i << " 年,Cleo的投资价值才能超过Daphne的投资价值" << endl;
	cout << "此时Daphne的投资价值为" << Dinterest << endl;
	cout << "此时Cleo的投资价值为" << Cinterest << endl;
}

5、

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

int main()
{
	array<int, 12>num = {0};
	int all=0;
	string month[12] = {"一月份","二月份","三月份" ,"四月份" ,"五月份" ,"六月份" ,"七月份" ,"八月份" ,"九月份","十月份","十一月份","十二月份"};
	for (int i = 1; i <= 12; i++)
	{
		cout << i << "月份的销售量为:" << endl;
		cin >>num.at(i-1);
		all += num.at(i-1);
	}

	cout << "这一年的销售情况为:" << all << endl;

}

7.用vs编辑有超多警告

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

struct car {
	string name;
	int years;
};

int main()
{
	int num;
	cout << "请输入有多少辆车" << endl;
	cin >> num;
	car *p= new car[num];
	
	for (int i = 0; i <num; i++)
	{
		cout << "Car #" << i+1<<endl;
		cout << "Please enter the make: ";
		cin.ignore();
		getline(cin, p[i].name);
		cout << endl;
		cout << "Please enter the year made: ";
			cin >> p[i].years;
	}
	cout << "Here is your collection: " << endl;

	for (int i = 0; i < num; i++)
	{	
		cout << p[i].years << p[i].name << endl;
	}
}

8、

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
	int i=0;

	const char arr[20] = "done";
	char arr2[20];

	while (strcmp(arr, arr2) != 0)
	{
		cout << "Enter words (to stop,type the word done): " << endl;
		cin >> arr2;
		cin.get();
	
		i++;
	}

	cout << "You entered a total of " << i-1 << " words";

	return 0;
}

9、编写一个满足前一个练习中描述的程序,但使用string对象而不是字符数组。请在程序中包含头文件string,并使用关系运算符来进行比较测试。

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str1 = "done";
	string str2;
	int counter = 0;
	while (str1 != str2)
	{
		cout << "Enter words (to stop,type the word done):" << endl;
		cin >> str2;
		cin.get();
		counter++;
	}
	cout << "You entered a total of " << counter - 1 << endl;
}

10.编写一个使用嵌套循环的程序,要求用户输入一个值,指出要显示多少行。然后,程序将显示相应行数的星号,其中第一行包括一个星号,第二行包括两个星号,依此类推。每一行包含的字符数等于用户指定的行数,在星号不够的情况下,在星号前面加上句点。该程序的运行情况如下:
Enter number of rows: 5
....*
...**
..***
.****
**** 
 

#include<iostream>
using namespace std;
int main()
{
	int i = 1,j=1,k=1,row;
	cout << "Enter number of rows: " << endl;
	cin >> row;
	
	while (i <= row)
	{
		while (j <= row - i)
		{
			cout << ".";
			j++;
		}
		j = 1;
		while (k <= i)
		{
			cout << "*";
			k++;
		}
		k = 1;
		cout << endl;
		i++;
	}
	return 0;
}

 第六章

一、复习题

1、第二种比第一种要好在代码执行效率高上。对于第一种情况而言,进入循环体之后,判断完第一个 if 之后还要判断第二个 if,并且不论 ch 是否为空格。但对于第二种情况而言,一旦 ch 就是空格,则只判断一次 if,而后面的 else if 语句将被省略掉。

2、就数值而言,两者是相同的,但 ++ch 输出的是字符,但 ch+1 输出的将是数字,但仍然可以用 char (ch+1) 将其转换为字符。

3、注意 while 循环体内部的 if 判断语句使用的是赋值符号 ‘=’,而不是相等判断符 ‘==’,因此在第二次输出的时候所有的 ch 都将被替换为 ‘$’。所以每循环一次相应的 ct1 和 ct2 的值都将等同地加 1,因此最后的结果是 ct1 和 ct2 是完全一样的。

4、

 int weight;
	   (weight >= 115) && (weight < 125);

		char ch;
		ch = 'q' || 'Q';

		x % 2 == 0 && x != 26

	    x % 2 == 0 && x % 26 != 0;

		1000 < donation < 2000 || guest == 1;

		(ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');

5、如果 x 为 bool 值,则 !!x 与 x 是一样的。但如果 x 为其它的不为 0 或 1 的值,则不一样。比如 x=2,则 !x=0,则 !!x=1,显然不再等于 x。

6、

#include<iostream>
using namespace std;

int main()
{
	int x;
	cin >> x;
	if (x >= 0)
		cout << x << endl;
	else if (x < 0)
		cout << -x << endl;
	return 0;
}

7、

#include<iostream>
using namespace std;

int main()
{
	char ch=EOF;
	int a_grade=0, b_grade=0, c_grade=0, d_grade=0, f_grade=0;
	    
		for (int i = 0; ch != 'S'; i++)
		{
			cout << "输入任意字符(输入S时程序停止)" << endl;
			ch = cin.get();
			cin.get();
			switch (ch)
			{
			case 'A':a_grade++; break;
			case 'B':b_grade++; break;
			case 'C':c_grade++; break;
			case 'D':d_grade++; break;
			case 'F':f_grade++; break;
			default:cout << "你刚刚输入的字符不在统计之内"<<endl;
			}
		}
	cout << "a_grade=" << a_grade << endl;
	cout << "b_grade=" << b_grade << endl;
	cout << "c_grade=" << c_grade << endl;
	cout << "d_grade=" << d_grade << endl;
	cout << "f_grade=" << f_grade << endl;

	return 0;
}

8、如果使用整数标签,且用户输入了非整数(比如 q),则程序将因为整数输入不能处理字符而挂起。但是如果使用字符标签,而用户输入了整数(如 5),则字符输入将 5 作为字符处理。然而,switch 语句的 default 部分将提示输入另一个字符。

9、

#include<iostream>
using namespace std;

int main()
{

	    char ch=EOF;
	
		for (int line = 0; ch != '\n'; line++)
		{
			ch = cin.get();
			cin.get();
		}
	return 0;
}

二、编程练习

1、编写一个程序,读取键盘输入,直到遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大写(别忘了cctype函数系列)。

#include<iostream>
#include<cctype>
using namespace std;

int main()
{
	char ch;
	cin.get(ch);
	while (ch != '@')
	{
		if (isdigit(ch))
		{
			cin.get(ch);
			continue;
		}
		else if (isupper(ch))
		{
			ch=tolower(ch);
		}
		else if(islower(ch))
		{
			ch = toupper(ch);
		}
		cout << ch << endl;
		cin.get(ch);
	}

	return 0;
}

3、编写一个菜单驱动程序的雏形。该程序显示一个提供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
Please enter a c, p, t, or g: t
A maple is a tree.

#include<iostream>
using namespace std;

int main()
{
	cout << "Please enter one of the following choice:" << endl;
	cout << "including c,p,t,g"<<endl;
	char input;
	cin >> input;
	
	switch (input)
	{
	case 'c':cout << "A maple is a carnivore"; break;
	case 'p':cout << "A maple is a pianist"; break;
	case 't':cout << "A maple is a tree"; break;
	case 'g':cout << "A maple is a game"; break;
	default:cout<<"Please enter a c,p,t,or g: ";
	}
	
	return 0;
}

4. 加入Benevolent Order of Programmer后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名了解他(她)。请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序时,请使用下面的结构:
// Benevolent Order of Programmer name structure
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 Programmer Report
a. display by name        b. display by title
c. display by bopname  d. display by preference
q. quit
Enter your choice: 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 rsize=40;
const int usersize = 5;
char input;

void cout_fullname();
void cout_titlename();
void cout_bopname();
void cout_preference();

struct bop
{
	char fullname[rsize];//real name
	char title[rsize];//job title
	char bopname[rsize];//secret BOP name
	int preference;//0=fullname,1=title,2=bopname
};
bop bop_user[usersize] =
{

	{"Wimp Macho","Programmer","MIPS",0},

	{"Raki Rhodes","Junior Programmer",1},

	{"Celia Laiter","","MIPS",2},

	{"Hoppy Hipman","Analyst Trainee","",1},

	{"Pat Hand","","LOOPY",2},

};//定义常量,定义结构体初始化bop数组信息

int main()
{
	cout << "Enter your choice :" << endl;
	cin>>input;
	
	while (input != 'p')
	{
		switch (input)
		{
		case 'a':cout_fullname(); break;
		case 'b':cout_titlename(); break;
		case 'c':cout_bopname(); break;
		case 'd':cout_preference(); break;
		default:cout << "That's not a choice." << endl;
		}
		cin >> input;
	

		
	}
	return 0;
}

void cout_fullname()
{
	for (int i = 0; i < 5; i++)
	{
		cout << bop_user[i].fullname << endl;
	}
}

void cout_titlename()
{
	for (int i = 0; i < 5; i++)
	{
		cout << bop_user[i].title << endl;
	}
}

void cout_bopname()
{
	for (int i = 0; i < 5; i++)
	{
		cout << bop_user[i].bopname << endl;
	}
}

void cout_preference()
{
	for (int i = 0; i < 5; i++)
	{
		if (bop_user[i].preference = 0)
			cout << bop_user[i].fullname << endl;
		else if (bop_user[i].preference = 1)
			cout << bop_user[i].title << endl;
		else
			cout << bop_user[i].bopname << endl;
	}
}

5. 在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>
using namespace std;

int main()
{
	double input;
	cout << "请输入你的收入" << endl;
	cin >> input;
	
	while (input>=0)
	{
		cout << "请输入收入" << endl;
		if (input <= 5000)
			cout << 0 << endl;
		else if (5000 < input <= 15000)
			cout << (input - 5000) * 0.1 << endl;
		else if (15000 < input <= 35000)
			cout << 10000 * 0.1 + (input - 15000) * 0.15 << endl;
		else
			cout << 10000 * 0.1 + 20000 * 0.15 + (input - 35000) * 0.2 << endl;
		cin >> input;
	}

	return 0;
}

6. 编写一个程序,记录捐助给“维护合法权利团体”的资金。该程序要求用户输入捐赠者数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被储存在一个动态分配的结构数组中。每个结构有两个成员:用来储存姓名和字符数组(或string对象)和用来存储款项的double成员。读取所有的数据后,程序将显示所有捐款超过10000的捐献者的姓名及其捐款数额。该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Patrons)。然后,程序将列出其他的捐款者,该列表要以Patrons开头。如果某种类型没有捐献者,则程序将打印单词“none”。该程序只显示这两种类别,而不进行排序。
 

#include<iostream>
#include<string>
#include<vector>
using namespace std;


struct PatronsIN {
	string name;
	double num;
};

int main()
{
	
	int IfEnd = 0;
	int num = 0;
	vector<PatronsIN>people;
	cout << "输入捐款者的信息" << endl;
	PatronsIN temp;
	while (IfEnd==0)
	{
		cout << "输入捐款者姓名" << endl;
		cin>>temp.name;
		cout << "输入捐款者捐款数量" << endl;
		cin >> temp.num;
		people.push_back(temp);
		cout << "是否结束输入?结束输入1,不结束输入0." << endl;
		cin >> IfEnd;	
	} 

	num = people.size();

	cout << "Grand Patrons" << endl;
	for (int i = 0; i <num; i++)
	{
		if (people[i].num >= 1000)
			cout << people[i].name <<"   "<<people[i].num << endl;
	}

	cout << "Patrons" << endl;
	for (int i = 0; i < num; i++)
	{
		
		if (people[i].num <1000)
			cout << people[i].name << "   " << people[i].num << endl;
	}

	return 0;
}

第七章

 1、要使用C++函数,必须完成如下工作:提供函数定义、提供函数原型、调用函数。

2、

void igor();
float tofu(int x);
double mpg(double x, double y);
long summation(long arr[], int size);
double doctor(const char* pr);
void ofcourse(boss BOSS);
char* plot(map* pmap);

3、

void IniitalizeArray(int Arr[], int Size, int Value)
{ 
	for (int i = 0; i < Size; i++)
		Arr[i] = Value; 
}

 4、

void InitializeArray(int* Begin, int* End, int N)
{ 
	for (int* pt = Begin; pt != End; pt++)
		*pt = N;
}

5、

#include<iostream>
using namespace std;

double fun(double arr[], int size);
int main()
{

	double arr[10] = { 1,2,3,4,5,6,7,8,9,0 };
	double x;
	x=fun(arr, 10);
	cout << x;
	return 0;
}


double fun(double* arr,int size)
{
	int max=arr[0];

	for (int i = 0; i < size; i++)
	{
		if (arr[i] > max)
			max = arr[i];

	}
	return max;
}

6、

如果某个函数的参数为指针,则当指针指向原始数据的地址时,则就很有可能在函数体内故意或者非故意地“篡改”原始数据,因此将 const 限定符作用于指针时就可以防止这种“恶意”的篡改。但是对于基本数据类型而言,传递给函数的并不是原始数据本身,而是原始数据的“拷贝”,或者称之为副本,因此在这种按值传递的过程中,原始数据将得到保护。

7、有指针形式,比如这样的定义 char* str; 也有数组形式,比如 char str[]; 还有字符串的字面值形式。这三种形式实际上都按照指针的方式进行操作。

8、

#include<iostream>
using namespace std;

int replace(char*str,char c1,char c2);
int main()
{
	char arr[] = { 'q','w','e','t','t' };
	int num =replace(arr, 't', 'a');
	cout << num;
	
	return 0;
}


int replace(char* str, char c1, char c2)
{
	
	int num = 0,j=0;
	num=strlen(str);
	
	for (int i = 0; i < num; i++)
	{
		if (str[i] == c1)
		{
			str[i] = c2;
			j++;
		}
	}
	return j;
}

9、由于C++将“pizza”解释为其第一个元素的地址,因此使用 * 运算符将得到其第一个元素的值,即字符 p。同理,“taco”也将被解释为第一个元素的地址,因此“taco”[2]表示第二个元素的值,即字符c,也就是说字符串常量的行为与数组名相同。

10、如果要按值传递结构 glitz,则只需要传递结构名 glitz即可。要传递它的地址的话就必须得使用取地址运算符 &glitz。按值传递仍然会像基本数据类型那样使用该结构体的副本,这将自动保护原始数据,但是当结构很大时,这种“拷贝”行为将会很耗时间和内存。当按地址传递时,虽然可以节省时间和内存,但是不能够保护原始数据,除非对函数参数使用 const 限定符。另外,按值传递意味着可以使用常规的结构成员表示法,但按指针传递则必须间接成员运算符。

//按值传递则是传递他的类型,然后glitz作为参数进行传递。按地址传递则是参数使用结构指针。

按值传递的好处是不会修改原结构变量,按地址传递的好处正好是可以在函数内修改原结构变量。

假如结构类型是abc,则声明结构是abc glitz;

按值传递函数原型假如为:void mmm(abc);

按地址传递函数原型假如为:void mmm(abc*);

glitz作为参数时,按值是glitz,按地址则为&glitz。

补充:按值传递将自动保护原始数据,但这是以时间和内存为代价的(因为要复制副本),按地址传递可节省内存和时间,但不能保护原始数据,解决办法是使用const限定符。

11、int judge(int (*pf)(const char*));

12、

#include<iostream>
using namespace std;


struct application {
	char name[30];
	int credit_rating[3];
};


void fun1(application a)
{

	cout << a.credit_rating << endl;//输出数字名,就是输出第一个元素地址
	cout << a.name << endl;//输出字符串名,就是输出整个字符串
	
}

void fun2(application* a)
{
	cout << a->credit_rating << endl;
	cout << a->name << endl;
	
}

int main()
{
	application factor = { "liyufeng",{0,1,3} };
	cout << "以下内容是将application结构作为参数,并显示该结构的内容:" << endl;
	fun1(factor);
	cout << "以下内容是将application结构的地址作为参数,并显示该结构的内容:" << endl;
	fun2(&factor);
	return 0;
}

13、typedef void (*p_f1)(applicant *);p_f1 p1=f1;typedef const char* (*p_f2)(const applicant*,const applicant*);p_f2 p2=f2;p_f1 ap[5];p_f2 (*pa)[10];

二、编程练习

1、

#include<iostream>
using namespace std;

double  average(int a, int b)
{
	double ave;
	ave = 2.0 * a * b / (a + b);
	return ave;
}

int main()
{
	int a, b;
	cin >> a >> b;
	//cout << a << b << endl;
	while (a != 0 && b != 0)
	{
		cout<<"此时的调和平均数为: " << average(a, b) << endl;
		cin >> a >> b;
	}
	cout << "你已经输出0,此程序结束" << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值