1. 程式人生 > >第四章 C++簡單題目

第四章 C++簡單題目

C4-1 最大公約數

 

(100/100 分數)

題目描述

求兩個正整數a 和 b的最大公約數。

要求使用c++ class編寫程式。

輸入描述

兩個正整數a,b,並且1=<a,b <=10000

輸出描述

a和b的最大公約數

樣例輸入

 

1000 1000

樣例輸出

1000
#include <iostream>
using namespace std;
class Integer {
private:
	int _num;
public:
	//建構函式
	Integer(int num) {
		_num = num;
	}
	//計算當前Integer 和 b之間的最大公約數
	int gcd(Integer b) {
		int c = b._num, d;
		_num>c ? d = c : d = _num;
		while ((_num%d != 0) || (c%d != 0))
			d--;
		return d;
		
	}
};

int main() {
	int a, b;
	cin >> a >> b;
	Integer A(a);
	Integer B(b);
	cout << A.gcd(B) << endl;
	return 0;
}

C4-2 反轉整數

 

(100/100 分數)

題目描述

對於輸入的一個正整數,輸出其反轉形式

要求使用c++ class編寫程式。

輸入描述

一個正整數a ,且1=<a<=1,000,000,000

輸出描述

a的反轉形式

樣例輸入

 

1011

樣例輸出

1101
#include<iostream>
using namespace std;

class Integer {
private:
	int _num;
	//getLength()函式獲取_num長度
	int getLength() {
		int i=0;
		int b = _num;
		while (b != 0) {
			b = b/ 10;
			i++;
		}
		return i;
	}
public:
	//Integer類建構函式
	Integer(int num) {
		_num = num;
	}
	//反轉_num
	int inversed() {
		int t = getLength();
		int tmp = _num;
		int a = 0;
		for (int i = 0; i < t; i++) {
			a = a * 10 + tmp % 10;
			tmp /= 10;
		}
		return a;
		
	}
};

int main() {
	int n;
	cin >> n;
	Integer integer(n);
	cout << integer.inversed() << endl;
	return 0;
}

C4-3 一元二次方程求解

 

(100/100 分數)

題目描述

對於一元二次方程ax^2 + bx + c = 0,解可以分為很多情況。

若該方程有兩個不相等實根,首先輸出1,換行,然後從小到大輸出兩個實根,換行;

若該方程有兩個相等實根,首先輸出2,換行,然後輸出這個這個實根,換行;

若該方程有一對共軛復根,輸出3,換行;

若該方程有無解,輸出4,換行;

若該方程有無窮個解,輸出5,換行;

若該方程只有一個根,首先輸出6,換行,然後輸出這個跟,換行;

要求使用c++ class編寫程式。

#include <iostream>
#include<math.h>
#include <stdio.h>
using namespace std;
class Equation {
private:
	int _a, _b, _c;
public:
	Equation(int a, int b, int c) {
		_a = a;
		_b = b;
		_c = c;
	}
	void solve();
};

void Equation::solve() {
	if (_a == 0) {
		if (_b == 0)
		{
			if (_c == 0) cout << "5" << endl;
			else cout << "4" << endl;
		}
		else {
			cout << "6" << endl;
			printf("%.2f\n", (float)-_c / _b);
		}
	}
	else {
		int theta;
		theta = _b * _b - 4 * _a*_c;
		double j = (-_b - sqrt(theta)) / 2.0 / _a;
		double k = (-_b + sqrt(theta)) / 2.0 / _a;
		if (theta >= 0) {
			if (theta > 0) {
				cout << "1" << endl;
				if(j<k)
				printf("%.2f %.2f\n", j, k);
				else 
					printf("%.2f %.2f\n", k, j);
			}
			else {
				cout << "2" << endl;
				printf("%.2f\n", -_b / 2.0 / _a);
			}
		}
		else cout << "3" << endl;
	}


}
int main() {
	
    int a, b, c;
    cin >> a >> b >> c;
	Equation tmp(a, b, c);
	tmp.solve();
	return 0;
}