C++基础编程DAY16(day)

35、掷骰子10000次,统计得到各点数的次数

//掷骰子10000次,统计得到各点数的次数

#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;

/* 获得随机数1-6 */
int get_randomNO()
{
	//int a;
	//a = rand()%6 + 1;
	//cout << rand() << endl;
	return rand()%6 + 1;
}

int main()
{
	int i,a[6] = {0};
	unsigned seed;//只保存非负整数
	seed = time(0);//用time()获取种子,每次运行时得到不同的种子
	srand(seed);//在 rand 被调用之前,srand 函数要先被调用,并且 srand 在整个程序中仅被调用一次
	for(i=0; i<10000; i++)
	{
		switch(get_randomNO())
		{
		case 1: a[0]++; break;//continue;//break;
		case 2: a[1]++; break;//continue;//break;
		case 3: a[2]++; break;//continue;//break;
		case 4: a[3]++; break;//continue;//break;
		case 5: a[4]++; break;//continue;//break;
		case 6: a[5]++; break;//continue;//break;
		default: cout << "error" << endl;
		}
		//cout << "验证for循环中的switch的break和continue作用范围" << endl;
	}
	for(i=0; i<6; i++)
		cout << a[i] << endl;
	system("pause");
	return 0;
}

36、编写函数distance,计算两点(x1,y1)和(x2,y2)之间的距离

//编写函数distance,计算两点(x1,y1)和(x2,y2)之间的距离。

#include<iostream>
#include<stdlib.h>
#include<math.h>

using namespace std;

double get_Distance(int *p, int *q)
{
	//double d;
	//cout << p[0] << "," << p[1] << "," << q[0] << "," << q[1] << endl;
	//cout << pow(double(q[1]-p[1]),2) << "," << pow(double(q[0]-p[0]),2) << endl;
	//d = sqrt(pow(double(q[1]-p[1]),2)+pow(double(q[0]-p[0]),2));
	return sqrt(pow(double(q[1]-p[1]),2)+pow(double(q[0]-p[0]),2));
}

int main()
{
	int a[2],b[2];
	cin >> a[0] >> a[1] >> b[0] >> b[1];
	cout << a[0] << a[1] << b[0] << b[1] << endl;
	cout << get_Distance(a,b) << endl;
	system("pause");
	return 0;
}

题目来源:50道C/C++编程练习题及答案

总结

1、使用srand()、rand()获得随机数,要将随机数的范围限制在 1 和某个最大值 max 之间的整数,可以使用以下公式:number = rand() % max + 1;
参考:C++随机数(rand和srand)函数用法详解
2、for循环中的switch的break和continue作用范围:break的作用仅仅对switch有作用,并没有跳出for循环。而continue的作用域包含for循环内的其他语句;
参考:for循环中的switch的break和continue作用范围
3、函数pow()用法:pow(底数,指数)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值