void函数
void用于修饰不返回值的函数
例如直接输出在屏幕上的函数
void函数中可以包含return,但是和一般函数不同,在void函数中return是用来终止函数调用的
传引用参数
#include "stdafx.h"
#include <iostream>
using namespace std;
void exm(int a,int& b);
int main()
{
int m,n;
m = ;
n = ;
exm(m,n);
cout<<m<<endl;
cout<<n<<endl;
}
void exm(int a,int& b){
a=;
b=;
}
如上函数,a是传值参数,b是引用参数
m = 1;n = 1;是给变量m,n分配了一个内存空间,假定为100和101,此时地址为100和101的空间里数据是1,此时调用函数exm,a是传值参数,所以又给a划了一个内存空间102,里面数据一开始也是1,b是引用参数,让b的内存空间也是101,和n一致,然后分别让a,b为10,改变的是内存空间101和102,并没有动100,所以最后输出为1,10
使用过程抽象
将函数设计成黑盒那样使用,只需查看注释,不需要了解主体的任何细节
注释规范化
void swap(int& a,int& b);
//前条件:a,b已被赋值
//后条件:a,b的值进行了交换
向以上代码一样,将注释分解成两种,前条件和后条件,前条件指出函数需要满足的条件,后条件描述函数调用的结果
测试和调用函数
每一个函数都应该独立于程序其他部分设计、编码和测试,每个函数都视为独立单元
驱动程序,指专门用来测试函数的程序
测试函数的时候,有时不得不用到其他尚未编写或测试的函数。这时,提供可以使用其他函数的简化版本,成为存根函数
常规调试技术
课后编程第九题
#include "stdafx.h"
#include <iostream>
using namespace std;
int money=;
//定义成公共变量,方便调用
int rollDice();
//前条件:没有
//后条件:输出一个一到十的随机数
void playerTurn(int wager,bool& bust1,int& total);
//前条件:wager已赋值,bust1赋值为ture,total为两次rollDice()函数的返回值
//后条件:返回total,bust1的值
void houseTurn(bool& bust2,int& total);
//前条件:bust2赋值为ture,total为0
//后条件:返回total,bust1的值
int main()
{
while(money>){
int w=;
cout<<"请输入赌注:"<<endl;
cin>>w;
int sum = rollDice()+rollDice();
int house = ;
bool bust=true;
playerTurn(w,bust,sum);
if (bust==false)
{
cout<<"您的总点数为:"<<sum<<endl;
cout<<"您输了"<<endl;
money = money -w;
}
else{
bust = true;
houseTurn(bust,house);
if (bust==false)
{
cout<<"您赢了"<<endl;
money = money + w;
}
else{
if (sum>house)
{
cout<<"您赢了"<<endl;
money = money + w;
}
if (sum==house)
{
cout<<"平局"<<endl;
}
if (sum<house)
{
cout<<"您输了"<<endl;
money = money -w;
}
}
}
bust = true;
cout<<"您的余额为:"<<money<<endl;
}
cout<<"您输光了"<<endl;
}
int rollDice(){
int roll;
roll = (rand() % ())+ ;
if (roll>=)
{
roll = ;
}else{
if (roll==)
{
roll = ;
}
}
return roll;
}
void playerTurn(int wager,bool& bust1,int& total){
if (total>)
{
bust1 = false;
cout<<"您爆点了,您的总点数为"<<total<<endl;
money = money -wager;
}
while(total<=){
cout<<"您的总点数为:"<<total<<endl;
char a;
cout <<"是否要牌(Y/N)"<<endl;
cin>>a;
if (a=='Y')
{
total = total +rollDice();
}
if (a=='N')
{
return;
}
}
if (total>)
{
bust1 = false;
}
}
void houseTurn(bool& bust2,int& total){
total = rollDice();
cout<<"庄家摸一张牌,庄家点数为:"<<total<<endl;
while(total<){
total =total+ rollDice();
cout<<"庄家摸一张牌,庄家点数为:"<<total<<endl;
}
if (total>)
{
bust2 = false;
}
}