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(底数,指数)