1. 程式人生 > >資料結構殷人昆程式設計練習第一章概論

資料結構殷人昆程式設計練習第一章概論

1.15 求三個整數中的最大、最小和中間數。

#include<iostream>
using namespace std;

void fun(int a, int b, int c){
	int max, min, center;
	if (a > b&&a > c){
		max = a;
		if (b > c){min = c; center = b;}
		else{ min = b; center = c; }
	}
	if (b > a&&b > c){
		max = b;
		if (
a > c){ min = c; center = a; } else{ min = a; center = c; } } else{ max = c; if (a > b){ min = b; center = a; } else{ min = a; center = b; } } cout << "max: " << max << endl; cout << "center: " << center << endl; cout << "min: " << min <<
endl; } void main(){ int x, y, z; cout << "please enter three int number: "; cin >> x >> y >> z; fun(x, y, z); system("pause"); }

1.16 比較兩個整數大小,並求其時間複雜度

#include<iostream>
using namespace std;

void compare(int a, int b){
	if (a > b)
		cout << ">"
; if (a < b) cout << "<"; if (a == b) cout << "=="; } // 時間複雜度O(1) void main(){ int a, b; cout << "please enter two int number: "; cin >> a >> b; compare(a, b); system("pause"); }

1.17 統計陣列中元素落在不同區間的個數

#include<iostream>
using namespace std;

void fun(int a[],int n)
{
	int cnt1=0, cnt2=0, cnt3=0, cnt4=0, cnt5=0;
	for (int i = 0; i < n; ++i)
	{
		if (0 <= a[i] && a[i] <= 20) cnt1 += 1; 
		if (20 < a[i] && a[i] <= 50) cnt2 += 1;
		if (50 < a[i] && a[i] <= 80) cnt3 += 1;
		if (80 < a[i] && a[i] <= 130) cnt4 += 1;
		if (130 < a[i] && a[i] <= 200) cnt5 += 1;
	}
	cout<< "0-20: " << cnt1 << '\n'
		<< "21-50: " << cnt2 << '\n'
		<< "51-80: " << cnt3 << '\n'
		<< "81-130: " << cnt4 << '\n'
		<< "131-200: " << cnt4 << '\n';
}

void main()
{
	const int n = 10;
	int a[n] = { 101, 23, 1, 66, 78, 35, 99, 170, 121, 55 };
	fun(a, n);
	system("pause");

}