C++编程题目 定义一个类coin 模拟翻硬币游戏
发布网友
发布时间:2022-05-07 04:03
我来回答
共2个回答
热心网友
时间:2023-10-14 20:41
#include <stdio.h>
class COIN
{
public:
COIN(int n1,int k1){
n = n1;
k = k1;
a = new int[n];
for(int i = 0; i < n ; i++){
a[i] = 1;
}
}
~COIN(){
delete []a;
}
void fun(){
int i = 0;
for(int j = 1 ; j <= k ;j++){
i = (j - 1) % n; //写为 i = j%n 亦可
if( ! ( j % 3) ){
a[i] = 1 - a[i] ;
continue;
}
if( ! (j % 5)){
a[i] = 1 - a[i];
continue;
}
}
}
void print(){
int i;
for(i = 0 ; i < n - 1 ; i ++){
printf("%d ",a[i]);
}
printf("%d\n",a[i]);
}
private:
int * a;
int n;
int k;
};
int main ()
{
COIN *a = new COIN(12,100);
a->fun();
a->print();
delete a;
}
热心网友
时间:2023-10-14 20:42
/*本人以上及测试过,没问题。不过你并没给定初始态,所以结果不一样。但若给定初始态,结果唯一。*/
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
class COIN
{ public:
COIN(int n1,int k1);
void func();
void prin();
~COIN(){};
private:
int *a,n,k;
};
COIN::COIN(int n1,int k1):n(n1),k(k1)
{
a=(int *)malloc(n1*sizeof(int) );
for(int i=0;i<n;i++)
a[i]=1;
}
void COIN::func()
{
for(int i=1;i<k+1;i++)
{int temp;
if(i%3 ==0 | i%5 ==0)
{temp=i%n; a[temp]=(a[temp]+1)%2 ;}
}
}
void COIN::prin()
{for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
}
void main()
{COIN b(12,100);
b.func();
b.prin();
}