C++程序是函數(shù)的集合。
每個函數(shù)都是一組語句。
聲明語句創(chuàng)建一個變量。賦值語句為該變量提供了一個值。
以下程序顯示了一個新的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é)果。
要將信息項存儲在計算機中,必須同時識別存儲位置以及信息所需的存儲空間。
程序有這個聲明語句(注意分號):
int examples;
賦值語句將值分配給存儲位置。
以下語句將整數(shù)25分配給由變量示例表示的位置:
examples = 25;
=符號稱為賦值運算符。
C++的一個特點是可以連續(xù)使用賦值運算符。
例如,以下是有效的代碼:
int a; int b; int c; a= b = c = 88;
賦值從右到左工作。
第二個賦值語句表明您可以更改變量的值:
examples = examples - 1; // modify the variable
以下代碼使用cin(發(fā)音為“see-in"),輸入對應的cout。
此外,該程序還顯示了另一種使用該功能的主機,即cout對象的方式。
#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é)果。
以下語句讀取值為變量。
cin >> examples;
iostream文件定義<< 操作符,以便您可以如下組合輸出:
cout << "Now you have " << examples << " examples." << endl;
這允許您在單個語句中組合字符串輸出和整數(shù)輸出。
結(jié)果輸出與以下代碼生成的輸出相同:
cout << "Now you have "; cout << examples; cout << " examples"; cout << endl;
您還可以通過這種方式重寫連接版本,將單個語句分四行:
cout << "Now you have " << examples << " examples." << endl;
以下代碼輸出表達式的值。
#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é)果。
更多建議: