C++ 語(yǔ)句

2018-03-22 15:28 更新

學(xué)習(xí)C++ - C++語(yǔ)句

C++程序是函數(shù)的集合。

每個(gè)函數(shù)都是一組語(yǔ)句。

聲明語(yǔ)句創(chuàng)建一個(gè)變量。賦值語(yǔ)句為該變量提供了一個(gè)值。

例子

以下程序顯示了一個(gè)新的cout功能。


#include <iostream> 

int main() { 
     using namespace std; 

     int examples;            // declare an integer variable 

     examples = 25;            // assign a value to the variable 
     cout << "I have "; 
     cout << examples;        // display the value of the variable 
     cout << " examples."; 
     cout << endl; 
     examples = examples - 1;  // modify the variable 
     cout << "I have " << examples << " examples." << endl; 
     return 0; 
} 

上面的代碼生成以下結(jié)果。

聲明語(yǔ)句和變量

要將信息項(xiàng)存儲(chǔ)在計(jì)算機(jī)中,必須同時(shí)識(shí)別存儲(chǔ)位置以及信息所需的存儲(chǔ)空間。

程序有這個(gè)聲明語(yǔ)句(注意分號(hào)):

int examples;

賦值語(yǔ)句

賦值語(yǔ)句將值分配給存儲(chǔ)位置。

以下語(yǔ)句將整數(shù)25分配給由變量示例表示的位置:

examples = 25;

=符號(hào)稱(chēng)為賦值運(yùn)算符。

C++的一個(gè)特點(diǎn)是可以連續(xù)使用賦值運(yùn)算符。

例如,以下是有效的代碼:

int a; 
int b; 
int c; 

a= b = c = 88; 

賦值從右到左工作。

第二個(gè)賦值語(yǔ)句表明您可以更改變量的值:

examples = examples - 1;  // modify the variable 

使用cin

以下代碼使用cin(發(fā)音為“see-in"),輸入對(duì)應(yīng)的cout。

此外,該程序還顯示了另一種使用該功能的主機(jī),即cout對(duì)象的方式。


#include <iostream> 

int main() 
{ 
     using namespace std; 

     int examples; 

     cout << "How many examples do you have?" << endl; 
     cin >> examples;                // C++ input 
     cout << "Here are two more. "; 
     examples = examples + 2; 
     
     // the next line concatenates output 
     cout << "Now you have " << examples << " examples." << endl; 
     return 0; 
} 

上面的代碼生成以下結(jié)果。

注意

以下語(yǔ)句讀取值為變量。

cin >> examples;

iostream文件定義<< 操作符,以便您可以如下組合輸出:

cout << "Now you have " << examples << " examples." << endl;

這允許您在單個(gè)語(yǔ)句中組合字符串輸出和整數(shù)輸出。

結(jié)果輸出與以下代碼生成的輸出相同:

cout << "Now you have "; 
cout << examples; 
cout << " examples"; 
cout << endl; 

您還可以通過(guò)這種方式重寫(xiě)連接版本,將單個(gè)語(yǔ)句分四行:

cout << "Now you have " 
     << examples 
     << " examples." 
     << endl; 

以下代碼輸出表達(dá)式的值。


#include <iostream> 
using namespace std; 
int main() {
     int x; 

     cout << "The expression x = 100 has the value "; 
     cout << (x = 100) << endl; 
     cout << "Now x = " << x << endl; 
     cout << "The expression x < 3 has the value "; 
     cout << (x < 3) << endl; 
     cout << "The expression x > 3 has the value "; 
     cout << (x > 3) << endl; 
     cout.setf(ios_base::boolalpha);   //a newer C++ feature 
     cout << "The expression x < 3 has the value "; 
     cout << (x < 3) << endl; 
     cout << "The expression x > 3 has the value "; 
     cout << (x > 3) << endl; 
     return 0; 
} 

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)