抛硬币实验做100次,记录硬币正反面朝上的情况。利用C++语言和Python语言编程对实验数据进行统计。分别统计正面朝上总次数、反面朝上总次数、正面连续朝上最大次数、反面连续朝上最大次数等。
抛硬币100次,记录情况:正面朝上为1,反面朝上为0;
程序的数据源要求有2个,一个是内置数据源,把抛硬币的100次实验数据内置在代码中,另一个是允许用户在键盘上实时输入实验数据;运行时允许用户选择数据源;
程序展示统计结果的界面后,提供用户选择:是退出程序,还是继续统计下一轮实验。
#include <bits/stdc++.h>
using namespace std;
int conti (int a[100],int x)
{
int k = 0,max = 0;
for (int i=0;i<100;i++){
if (a[i]==x){
k = k + 1;
if (max < k){
max = k;
}
}
else{
k = 0;
}
}
return max;
}
int sum (int a[100],int x){
int total = 0;
for (int i=0;i<100;i++){
if (a[i]==x){
total = total + 1;
}
}
return total;
}
main()
{
srand((int)time(NULL));
string choice = "继续统计下一轮数据" ;
string anwser;
int a[100],i=0;
while (choice == "继续统计下一轮数据") {
cout<<"请选择是否手动输入(输入Yes或者No):";
cin >>anwser;
if (anwser == "Yes"){
while(i<100){
cout<<"这次第"<<i+1<<"次试验结果:";
cin>>a[i];
if ((a[i]==0||a[i]==1 )){
i = i + 1;
}
else{
cout<<"输入错误,请重新输入"<<endl;
}
}
}
else if (anwser == "No"){
for (int x=0;x<100;x++){
a[x] = rand()%2;
cout<<"第"<<x<<"次的实验结果为:"<<a[x]<<endl;
}
}
cout<<"硬币正面朝上的次数为:"<<sum(a,1) <<endl;
cout<<"硬币正面朝下的次数为:"<<sum(a,0) <<endl;
cout<<"硬币连续朝上的最多次数为:"<<conti(a,1) <<endl;
cout<<"硬币连续朝下的最多次数为:"<<conti(a,0) <<endl;
cout<<"请选择‘退出程序‘或者‘继续统计下一轮数据‘" <<endl;
cin>>choice;
}
}
from random import *
from collections import *
def conti (ls,x):
k = 0
kmax = 0
for i in ls:
if i == x:
k = k + 1
if kmax<k:
kmax = k
else:
k = 0
return kmax
choice = ‘继续统计下一轮数据‘
while (choice==‘继续统计下一轮数据‘):
seed (randint(0,999))
print("是否手动输入:")
answer = input()
ls = []
if answer == ‘是‘:
i = 0
while(i<100):
print(‘这是第{}次的结果‘.format(i+1))
x = int(input())
if x in [0,1]:
ls.append(x)
i = i + 1
else:
print("输入错误,请重新输入")
elif answer == ‘否‘:
for i in range(100):
x = randint(0,1)
ls.append(x)
print(‘第{}次的实验结果为{}‘.format(i+1,x))
dic = Counter(ls)
print("硬币正面朝上的次数为:{}".format(dic[1]))
print("硬币正面朝下的次数为:{}".format(dic[0]))
print("硬币连续朝上的最多次数为{}".format(conti(ls,1)))
print("硬币连续朝下的最多次数为{}".format(conti(ls,0)))
print("请选择‘退出程序’或者‘继续统计下一轮数据’")
choice = input()
本文代码,仅供测试,不得抄袭转载
原文:https://www.cnblogs.com/Atsuhiro/p/14957119.html