2021年3月17日 星期三

C++ Lesson 1 Assignment(Suggested Answer)

 

C++ Lesson 1 Assignment

Suggested Answer

 


1.      Output the following on the screen

C++ is

 

Very useful!

 

解說: 輸出至螢幕的指令是 cout<<輸出資料。

如要換行的話,輸出資料是endl 便可以。

由於C++ 
輸出後,要換兩行,因此要輸出兩個endl

以上的指令,其實也可以寫成:

        cout<<”C++ “;

        cout<<endl;

        cout<<endl;

        cout<<”Very useful!”;

       

注意,必需要於int main() 前加上 using namespace std; ,否則每個cout指令前都要加std::,例如 std::cout<<”C++”;

 

2.      Output the following on the screen( 7 is the result of calculation)

3+4 is equal to

7


 

解說: cout<< 其實也可以輸出計算後的數值,不過如果要用作計算的話,數目字便不需要用” “ 包著,因此cout<<3+4; 的結果是 7,但cout<<”3+4”; 的輸出則是3+4

 

3.      Calculation of the area of a circle(use variable)

The radius of a circle is 2,

The output is as follow:

The area of this circle is 12.56. 


 

解說: 這題目指明要用變量(variable)處理,由於是整數值,因此宣告變量時便用

int r; 即是宣告一個名叫r的變量,變量的資料型態是整數(integer),用int

這題目不需要使用者自行輸入半徑(radius)的值,因此便於程式內把r 設定2(r=2;)

        輸出時,cout<<內輸入計算式,使用變量也可以,因此用cout<<r*r*3.14;

 

4.      Calculation of the area of a circle(the value of the radius is entered by user)

The output is as follow:

 

Enter your radius:

The area of your circle is:



解說: 這題目要求可讓使用者自行輸入半徑(radius)的值,因此需要用cin這指令。

cin>>r; 的作用是讓使用者輸入,然後把輸入的數字貯於r這變量內。

 

5.      Output a  number of “*” in one line. The value of the number is entered by user.

The output is as follow:

 

Enter a number:

*****



解說: 這題目要求讓使用自行輸入一個數目,方法跟以上題4相同啦。

然後,根據使用者輸入的數目,輸出相同數目的*

由於要不斷按數目不斷輸入*,因此要使用迴圈的指令。

for 是用以進行指定次數迴圈的指令。

For (i; i<=num; i=i+1){

}

i 代表開始時變量的值,i<=num 是執行迴圈內指令的條件,符合這條件的話便繼續執行,由於num是自行輸入的數目,i<=num的作用便是祇要i少於或等於num,便繼續執行輸出一粒*,最後的i=i+1的意思是執行一次迴圈後,會把i的值加1(留意,於C++程式,其實可以用i++取代 i=i+1 )

-------------------------------------------------------------------------------------------------

更多練習

沒有留言:

張貼留言

如何於C++產生亂數?

 如 何於 C++ 產生亂數 ?   以下是一個例子,輸出一個由 0-4 的亂數。留意,行號 2,3,8,9,10 及 11 是需要的。 備註 : 如要輸出 0-9 的話,把行 11 的 rand()%5 改成 rand()%10 便可以。   -----...