6.3 编写自己的fact函数
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string fact(char trueanswer)
{
switch (trueanswer)
{
case 'A'://这里是冒号
return "wrong answer";
break;
case 'B':
return "wrong answer";
break;
case 'C':
return"wrong answer";
break;
case 'D':
return"这都被你知道了";
break;
}
}
void main()
{
cout << "让你猜猜我的qq是多少" << endl;
cout << "A:123456788" << endl;
cout << "B"<<endl;
cout << "C" << endl;
cout << "D" << endl;
cout << "正确答案是?";
char givenanswer;
cin >> givenanswer;
string output = fact(givenanswer);
cout << output << endl;
}
6.4用户输入一个数字生成数字的阶乘。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int fact(int mynumber)
{
int number = 1;
int answer = 1;
for (; mynumber > 1; mynumber--)
{
answer *= mynumber;
}
return answer;
}
int main()//void 表示没有返回值老式写法 int main()表示返回值类型为int ,结尾要加上return 0;
{
cout << "请输入数字:";
int givennumber;
cin >> givennumber;
int output = fact(givennumber);
cout << givennumber << "的阶乘为:" << output << endl;
return 0;
}
6.6
局部静态变量:生命周期贯穿整个程序
普通局部变量:只存在于块执行期间,出了块自动销毁
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int fact()//函数的声明定义,空的形参
{
static int number = 0;//局部静态变量
number++;
return number;
}
void main()
{
for (int i = 0; i <= 10; i++)
{
cout << fact() << endl;
}
}
如果不加static 结果为1 1 1 1 1 1 1 1 1 1
C++最好使用引用类型的形参代替指针(
可以通过指针来修改它所指对象的值
)
七、类
7.4 编写一个类,自动返回姓名和住址
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class person
{
public:
person(string clientname, string clientadress);//声明初始化构造函数
string name;
string address;//内部变量
void showinfo()//类内定义成员函数
{
cout << name << "'s" << "adress is" << address << endl;
}
string& const getname()//返回姓名地址,只可访问 string类型变量的引用
{
return name;
}
string& const getaddress()
{
return address;
}
};
person::person(string clientname, string clientaddress) :name(clientname), address(clientaddress){};
//定义构造函数,初始化列表,定义内部变量
int main(int argc, char **argv)
{
person client1("mr.right", "your heart");
client1.showinfo();//调用成员函数显示信息
return 0;
}