天天看點

第五章 用函數完成所有子任務筆記

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;
    }
}