2018年9月,我开始学习C++语言,并坚持每天进行练习。我需要在此做一些笔记。
任务:练习C++的输入与输出
主要代码如下:
#include<iostream> //预处理命令,包含一个头文件
#include<string>
#include<math.h>
#define PRICE 30 //宏定义,定义PRICE为30 ,为练习06做准备
using namespace std;
//调用max()函数,为练习03做准备
double max(double x, double y)
{
if (x>=y) return x;
else return y;
}
int main(){
//编程01:练习字符型变量
string a = "Hello";
string b = "World";
string c; //should be ""
//print c the easy way
c = a+ " ";
cout << "c is: " << c << endl;
//print c the easy way
c += b;
cout << "c is: "<< c << endl;
//print c the primitive way
cout << "c is: " << c.c_str() << endl;
//print c's length
cout << "c's length is: " << c.length() << endl;
//print a empty line
cout << endl;
//print c character-by-character, making each character occupies one line
cout<< "c is: "<< endl;
for (int i=0; i<c.length(); i++)
cout<< c[i] <<endl;
//增加一个空行
cout << endl;
//编程02,目的:求两个整数的和
int d, e;
cout << "Enter two integers: ";
cin >> d >> e; //输入两个整数d和e
int result;
result= d + e;
cout <<"\n The sum of " <<d <<" + " << e <<" is " << result << " ." <<endl;
//编程03:练习调用函数
/* 调用max()函数 ,需要在程序开头写好
double max(double x, double y)
{
if (x>=y) return x;
else return y;
}
*/
double f, g, h;
cout<< "Input two numbers: " <<endl;
cin >> f >>g;
h= max(f, g);
cout<< "The value of h is equal to " << h << endl;
cout<< "The square root of h is: " <<sqrt(h) <<endl;
cout<< "\n";
//编程04:字符型变量的初始化
char c1, c2;
c1= 'a';
c2= 'A';
cout<< c1 <<"\n";
cout<< c2 <<"\n";
cout<< "\n";
//字符数据和整型数据之间的相互赋值
int i, j;
char k, l;
i='a'; j='b';
cout<< i <<" " <<j<< "\n";
cout<< char(i)<<" " << char(j) <<"\n"; //强制类型转换
k=97; l=98; //k和j虽然是字符型变量,但是我仍然可以拿小整数赋给它
cout<< "\n";
cout<< k << " " <<l <<"\n";
cout<< int(k) <<" " << int(l)<< "\n"; //强制类型转换
cout<< "\n";
k=i-32;
l=j-32;
cout<< k<< " " << l<< "\n";
cout<< int(k) << " " << int(l)<< "\n";
cout << "\n";
i=i-32;
j=j-32;
cout<< i <<" "<< j<< "\n";
cout<<i<<" "<< j<<" "<< k <<" "<<l<<"\n";
cout<<char(i)<< " "<< char(j)<< " "<< k <<" "<< l<< "\n";
cout<<i << " "<< j << " " << int(k)<< " "<< int(l)<< "\n";
//编程05:练习枚举型数据
cout<< "\n";
enum color{red, green, blue }; //red=0, green=1, blue=2;
color paintbrush=red; //定义一个color型变量,并赋值为red
if (paintbrush==0) //判断:paintbrush==red
cout<<"red paintbrush" <<"\n";
//编程05:练习浮点型数据
//浮点型数据float的有效数字为7位
cout<< "\n" ;
int num, total;
float v, r, m;
num=10;
total=num* PRICE; //total=300
cout << total<< "\n";
r=2.1; m=3.3; v=3.14159* r *r *m; //求圆柱体积
cout<< v <<"\n"; //45.7197,由于数据类型为float,单精度,仅保留7为有效数字
return 0;
}