close
  1. Write a complete program that prompts the user for the radius of a sphere, and calculates

and prints the volume of that sphere. Use an inline function sphereVolume that returns the result of the following expression: ( 4.0 / 3.0 ) * 3.14159 * pow( radius, 3 ).

 

Output should look as follows:

 

Enter the length of the radius of your sphere: 10

Volume of sphere with radius 10 is 4188.79

 

簡單說,題目要做的東西就是要計算球體容積,球體半徑的值由使用者訂或者是寫進程式裡面都可以。特殊要求是要用inline function完成。

題目不難,寫成一個 *.cpp 檔案也是可以的,不過...,依照之前的習慣,有時間我都會拆成三個檔案來寫。

 

Solution:

 

首先是表頭檔。表頭檔的觀念很簡單,基本上,就是讓整個程式的修改變得更容易,而對資料庫結構來說,也同時提供更強大的安全性。一般在寫program的時候,最簡單的寫法是把所有的運算資料跟方程式都寫在一起,但是這樣一但需要修改大型程式,或者是多人聯手開發一個大型程式的時候,就會出現很多問題。也覺得辦法,基本上就是用abstract date type (C語言)的方法構成程式;也就是說將一個程式拆成三個部分來寫。表頭檔宣告function 名稱,引用表頭檔之後,單獨將所有的 functions 寫在一起,然後在使用者可以看到的部分,單純的做出值的輸入與輸出就好。這樣一來,客戶不能隨意修改程式運作,整個程式也會再修改上面變得更輕鬆。

 

一般來說,表頭檔包含方程式的類型,方程式的名稱,以及方程式的內涵元素,簡單來說,就是為了宣告function而存在。

以下,就是非常簡單的表頭檔:

 

Calculator.h: 

double cube(double radius);

 

 

 

然後是置放functions的檔案:

 

CalculatorFunction.cpp:

#include "Calculator.h" //這邊要記得引用表頭檔,除非你把表頭檔寫在這個檔案的最上面

 

//下面的function基本上就是把所有的運算都包含進去了。因為pi=3.14159,不能算是一個integer型態的值,所以為了求出精度,我用double做為整個function的型態,也可以用float,兩者都可以輸出小數點。

 

double cube(double radius) {

     double Answer;

     double initial = 1.0;

     double a = 4.0/3.0;

     double b = 3.14159;

     Answer = a*b;

    for(double i = 0; i < 3; i++)

        initial = initial * radius; //這邊也可以寫成initial * = radius; 結果會完全一樣。

 

   

     return initial*Answer;

    

    

}

 

 

#include <iostream>

#include "Calculator.h" //一樣不要忘記引用表頭檔!

using namespace std;

 //#include <iostream>

//using namespace std;

基本上上面這兩行可以用來引用大部分函式庫中的函式,用了她就不需要考慮這種問題。不過這當然是偷懶的方法...。久了就會忘記甚麼樣的功能會在哪些函式庫裡面,哪一天說不定會為了這種小事情而哭泣喔XDDD

int main() {

 

     int radius = 0; //定義半徑變數的型態,並且先歸零。其實應該用double或者是float才對,因為說不定半徑也會有小數點。

    

     cout <<"\n\nStudnt name:\tYi-Siang Cheng\nStudent ID:\t7350\n\nPlease enter the number of the length of the radius of the sphere: ";

    cin >> radius;

 

     cout <<"The volume of sphere which the radius's length equal "<< radius <<" is: "

            <<cube(radius)//引用的方式很簡單,就直接寫上去就好。值得一提的是有關於變數的引用:基本上,不管你有多少變數,只要把變數名稱放進()中間,cube這個function都會把變數的值代進function 中的變數radius中,然後進行運算。

         << endl;

 

 

 

     system("pause");

    return 0;

}

arrow
arrow
    全站熱搜

    archerdevil 發表在 痞客邦 留言(0) 人氣()