【cpp】抛硬币(还有个bug未完善)

本文记录了作者初次尝试用C++编写抛硬币程序的经历,虽然目前程序中还有一个bug待解决,但已经迈出了学习C++的第一步。在Windows环境下进行的开发过程中,作者体验了调试和问题排查的过程。
摘要由CSDN通过智能技术生成

这是本人第一个cpp程序

//建议Windows运行
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
	int a = 1; //上限
	int b = 0; //下限
	int times = 1; //次数
	int zhengfan = 1; //正反
	int t = 1; //总次数

	srand(time(0));

	while (1)
	{
		int front = 0; //正面次数
		int back = 0; //反面次数
		t = 1;
		cout << "请输入次数,输入503202005退出程序:" << endl;
		cin >> times;

		if (times == 503202005)
		{
			break;
		}

		double be_t = clock();//开始计时

		while (t <= times)//循环抛硬币
		{
			t += 1;
			zhengfan = rand() % (2) + 0;
			if (zhengfan == 1)
			{
				front += 1;
			}
			else if (zhengfan == 0)
			{
				back += 1;
			}
		}

		double fi_t = clock();//停止计时
		double delta_t = (fi_t - be_t) / CLOCKS_PER_SEC;//计算时间单位毫秒

		/*尚未解决的bug,显示概率为零
		float pf = front * 100 / ( front + back );
		float pb = back * 100 / ( front + back );
		*/
		double f = 100 * front;
		double b = 100 * back;
		double pf = f / t;
		double pb = b / t;

		cout << "正面次数:" << front << "概率:" << pf << "%" << endl;
		cout << "反面次数:" << back << "概率:" << pb << "%" << endl;
		cout << "用时:" << fixed << delta_t << "秒" << endl;
		//DEBUG

		//DEBUG
		if (delta_t > 0)
		{
			cout << "速度:" << (front + back) / delta_t << "次/秒" << endl;
		}
		else
		{
			cout << "电脑太快了,计时太短无法计算QWQ." << endl;
		}
	}
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值