C 語言講稿 —— 各種有啟發性的 C 語言閱讀用小例子…
- Day 1 “Hello, Rukata … “
- Day 2 “Print Snow Pattern. … …”
- Day 3 “A problem in ACM..”
- Day 4 “Between the Circles …”
…
一組列印圖形的例子。主要用於熟悉 For 循環 和 if 條件語句。
介紹 「樂學網」 的一個練習,一步步優化到 O(n)。
引導設計一些幾何結構,在編碼過程中,提供儘可能多的 「最佳實踐」 方面的建議,開始偏向 「設計」 和 「表達」 的部分而暫跳過所有語言細節的部分… 等待時間。
4-1 : 設計一個結構用以描述圓,具有一個成員變數描述半徑,返回周長和面積的函數。[演示]
4-2 :
(1) 設計一個結構描述三角形,記錄三邊長,返回周長和面積。
(Point:面積函數的設計。)
(2)追加bool isRtTriangle() 函數返回是否是直角三角形。
增加 int type() 成員函數判斷三角形的類型。
(Point:規則化與對用戶的輸入做要求?… 三值函數的設計。)
4-3:繼續圓,在習題4-1的基礎上增加成員函數描述圓心坐標,增加函數 int f(Circle C1, Circle C2) 返回兩個圓之間的位置關係(。#)…
(Point:函數返回值具有某種神秘屬性?…)
#include
using namespace std;
const double PI = 3.14;
double sqr(double r){
return r*r;
}
struct Circle{
double r;
double f(){
return 2*PI*r;
}
double g(){
return PI*sqr(r);
}
};
Circle C;
int main(){
while (cin >> C.r){
cout << C.f() << " " << C.g() << endl;
}
}
#include
#include
using namespace std;
struct Triangle{
double a, b, c;
double f(){
return a + b + c;
}
double g(){
double p = f() / 2;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
};
Triangle T;
int main(){
while (cin >> T.a >> T.b >> T.c){
cout << T.f() << " " << T.g() << endl;
}
}
#include
#include
using namespace std;
int sign(double x){
if (x<0) return -1;
else if (x>0) return 1;
return 0;
}
struct Triangle{
double a, b, c;
Triangle(): a(0), b(0), c(0){
}
Triangle(double _a, double _b, double _c): a(_a), b(_b), c(_c){
if (a < b) swap(a, b);
if (a < c) swap(a, c);
if (b < c) swap(b, c);
}
double f(){
return a+b+c;
}
double g(){
double p = (a+b+c) / 2;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
int type(){
return sign(a*a - (b*b+c*c));
}
bool isRtTriangle(){ // . @
return type()==0;
}
// -1 : Ruijiao..
// 0 : Zhijiao
// 1 : Dunjiao..
};
int main(){
double a, b, c;
while (cin >> a >> b >> c){
Triangle T(a, b, c);
cout << T.type() << endl;
}
}
#include
#include
using namespace std;
const double PI = 3.14;
int sign(double x){
if (x<0) return -1;
else if (x>0) return 1;
return 0;
}
double dist(double x1, double y1, double x2, double y2){
return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
}
struct Circle{
double r;
double x0, y0;
double f(){
return 2*r*PI;
}
double g(){
return PI*r*r;
}
};
int f(Circle C1, Circle C2){
double d1 = dist(C1.x0, C1.y0, C2.x0, C2.y0); // 圓心距。@
double d2 = C1.r + C2.r; // 半徑和...
double d3 = fabs(C1.r - C2.r); //半徑差的絕對值..
if (d1 > d2) return 2; // 相離.
else if (d1 < d3) return -2; // 內含...
else if (d1 == d2) return 1; // 外切..
else if (d1 == d3) return -1; // 內切...
return 0; //相交.. Orz
}
Circle C1, C2;
int main(){
while (cin >> C1.x0 >> C1.y0 >> C1.r){
cin >> C2.x0 >> C2.y0 >> C2.r;
cout << f(C1, C2) << endl;
}
}