第三週上機實踐專案2——三角形類2
阿新 • • 發佈:2019-02-10
問題及程式碼
/* * Copyright (c) 2015, 煙臺大學計算機學院 * All rights reserved. * 檔名稱:test.cpp * 作 者:辛彬 * 完成日期:2015 年 3 月 22 日 * 版 本 號:v1.0 * * 問題描述:設計一個三角形類,請給出各成員函式的定義。 * 輸入描述:邊長。 * 程式輸出:周長和麵積。 */ #include<iostream> #include<Cmath> using namespace std; class Triangle { public: void setA(double x) { a=x; } void setB(double y) { b=y; } void setC(double z) { c=z; } bool isTriangle() { if(a+b>c&&a+c>b&&b+c>a) return true; else return false; } double getA() { return a; } double getB() { return b; } double getC() { return c; } double perimeter() { return a+b+c; } double area() { double p; p=(a+b+c)/2; return sqrt(p*(p-a)*(p-b)*(p-c)); } private: double a,b,c; //三邊為私有成員資料 }; int main() { Triangle tri1; //定義三角形類的一個例項(物件) double x,y,z; cout<<"請輸入三角形的三邊:"; cin>>x>>y>>z; tri1.setA(x); tri1.setB(y); tri1.setC(z); //為三邊置初值 if(tri1.isTriangle()) { cout<<"三條邊為:"<<tri1.getA()<<','<<tri1.getB()<<','<<tri1.getC()<<endl; cout<<"三角形的周長為:"<< tri1.perimeter()<<'\t'<<"面積為:"<< tri1.area()<<endl; } else cout<<"不能構成三角形"<<endl; return 0; }
執行結果: