参考《C++ Primer第4版》(中文版)
1.C++变量名规则:数字、字母、下划线构成,不能以数字开头,不能使关键字
书写习惯:全部小写,单词之间用下划线隔开:girl_student、worker_salary
2.变量名的初始化:
复制初始化:int a = 2;
直接初始化:int a(2); //更灵活,更高效
区别:对于一般的内建类型,这两种初始化基本上没有区别。但当用于类类型对象时,初始化的复制形式和直接形式有所不同:直接初始化直接调用与实参匹配的构造函数,复制初始化总是调用复制构造函数。复制初始化首先使用指定构造函数创建一个临时对象,然后使用复制构造函数将那个临时对象复制到正在创建的对象。
3.细节注意:对于不通类型初始化:int型默认为0,string型默认为空字符串
inta; int str; 则默认a = 0;str = “”;
4.声明和定义不同:声明只是表明有这样一个变量,定义才真正为变量分配内存空间。变量可以声明多次但只能定义一次。可以通过extern关键字声明变量名而不定义它:
extern int a; //声明不定义
int a; //声明并且定义
extern int a = 3; //虽然有extern但显然分配了内存空间所以也是定义
5.const修饰符 修饰常量。
与其他变量不同,普通变量在一个文件中声明后可以在另一文件(同一工程下)中使用,而const变量不可以。Const默认为文件局部变量.
每日三题:2012.07.27
(1).使用递归函数,求99+97+95+...+3+1之和。
(2). 写出加法计算的多个重载函数(int和double类型参数重载、两个数和一组数相加)
(3).职工类设计(class Staff)
数据成员: ID号、姓名、性别、年龄、部门、薪水
成员函数:构造函数、析构函数、查看职工信息、部门调整、薪水更改。
昨日三题解答:
1. 输入一个年份,判断平年还是闰年并输出结果。
/**
*名称:C++Review
*作者:TskyFree
*时间:2012年7月
*/
#include<iostream>
usingnamespace std;
intmain(void)
{
int year = 0;
cout << "请输入年份:";
cin >> year;
if((year%4==0&&year%100!=0)||year%400==0)
cout << "闰年" <<endl;
else
cout << "平年" <<endl;
system("pause");
return 0;
}
2.输入任意一组数(个数不定)求其最大值和最小值。
/**
*名称: C++Review
*作者:TskyFree
*时间2012年7月
*/
#include<iostream>
usingnamespace std;
boolcalculate(int* nums,int count,int &max,int &min);
intmain(void)
{
int* nums = NULL; //用户输入一组数的首址
int count = 0; //用户输入的个数
int max = 0; //最大值
int min = 0; //最小值
cout << "请输入数字个数";
cin >> count;
//输入一组数
cout << "请输入一组数:";
nums = new int[count];
for(int i = 0;i < count;++i)
cin >> *(nums+i);
//调用函数求值
if(calculate(nums,count,max,min))
{
//输出结果
cout << "\n最大值" << max<< endl
<< "最小值" << min<< endl;
}
else
cout << "出错!"<<endl;
system("pause");
return 0;
}
boolcalculate(int* nums,int count,int &max,int &min)
{
max = min = *nums;
for(int i = 0;i < count;++i)
{
if(max < *(nums+i)) //也可写成if(max<nums[i])
max = *(nums+i);
if(min > *(nums+i))
min = *(nums+i);
}
return true;
}
3.解数学灯迷。有以下算式 ABCD-CDC=ABC,其中ABCD均为一位非负整数,求ABCD的值。(结果:1098)
解法一:
/**
*名称:C++Review
*作者:TskyFree
*时间:2012年7月
*/
#include <iostream>
using namespace std;
int main(void)
{
cout<< "满足ABCD-CDC=ABC的ABCD为:";
for(inta = 0;a < 10;++a)
for(intb = 0;b < 10;++b)
for(intc = 0;c < 10;++c)
for(intd = 0;d < 10;++d)
if((1000*a+100*b+10*c+d)-(100*c+10*d+c)==(100*a+10*b+c))
if(a+b+c+d!= 0)//保证abcd不同时为0
cout<< a << b << c << d << "\t";
cout<< endl;
system("pause");
return0;
}
解法二:
/**
*名称:C++Review
*作者:TskyFree
*时间:2012年7月
*/
#include <iostream>
using namespace std;
int main(void)
{
inta = 0;
intb = 0;
intc = 0;
intd = 0;
intnum = 0;
cout<< "满足ABCD-CDC=ABC的ABCD为:";
for(num=1000;num<10000;++num)
{
a= num / 1000;
b= num / 100 % 10;
c= num / 10 % 10;
d= num % 10;
if(num-(c*100+d*10+c) == a*100+b*10+c)
cout<<num<< "\t";
}
cout<<endl;
system("pause");
return0;
}