假設我們骰骰子6000次我們要怎麼計數呢,昨天我們有用for和陣列來練習了,所以我們今天要用更多的陣列來在練習一次這個題目,因為昨天還是寫了printf六次,下程式碼
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(0));
int counter[6]={0};
int i,j;
for(i=1;i<=6000;i++)
{
int dice=rand()%6+1;
for(j=1;j<=6;j++)
{
if(dice==j)
{
counter[j-1]++;
}
}
}
for(j=1;j<=6;j++)
{
printf("%d: %d\n", j, counter[j-1]);
}
return 0;
}
上面的程式碼中,我們因為要骰骰子6000次所以我們用for迴圈來包,接著for包了if(dice==j)為什麼counter[j-1]呢,因為counter1等於counter[0]陣列是從0 1 2 3 4 5開始跑的,所以才是counter[j-1],我們下面printf也不用做六次,就是計算1有幾次、2有幾次...我們要印出的結果
#include <iostream>
#include <iomanip>
#include "BasePlusCommissionEmployee object"
using namespace std;
int main()
{
BasePlusCommissionEmployee;
employee("Bob", "Lewis","333-33-3333", 5000, .04, 300);
cout<<fixed<<setprecision(2);
cout<<"Employee information obtained by get functions: \n"
<<"\nFirst name is "<<employee.getFirstName()
<<"\nLast name is "<<employee.getLastName()
<<"\nSocial security number is "
<<employee.getSocialSrcurityNumber()
<<"\nGross sales is "<<employee.getGrossSales()
<<"\nCommission rate is"<<employee.getCommissionRate()
<<"\nBase salary is "<<employee.getBaseSalary()<<endl;
employee.setBaseSalary(1000);
cout<<"\nUpdated employee information output by print function: \n"
<<endl;
employee.print();
cout<<"\n\nEmployee's earings: $ "<<employee.earnings()<<endl;
}
上面的程式碼中我們將BasePlusCommissionEmployee類別實體化成為employee物件,並且傳遞“Bob" "Lewis"...以及300到建構子,分為當作名字 姓氏...,接著使用了類別的get函示取回該物件資料成員中的資料以供顯示輸出,接著在呼叫物件的setBaseSalary成員函示來更新底薪,成員函示setBaseSalary確認資料成員不能指定為負數,因為員工的底薪不能是負的,最後呼叫物件的print成員函示來更新過BasePlusCommissionEmployee資訊,並且讓earings來顯示收入