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

發佈了27 篇原創文章 · 獲贊 3 · 訪問量 847
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章