C++ 语句

2018-03-22 15:28 更新

学习C++ - C++语句

C++程序是函数的集合。

每个函数都是一组语句。

声明语句创建一个变量。赋值语句为该变量提供了一个值。

例子

以下程序显示了一个新的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; 
} 

上面的代码生成以下结果。

声明语句和变量

要将信息项存储在计算机中,必须同时识别存储位置以及信息所需的存储空间。

程序有这个声明语句(注意分号):

int examples;

赋值语句

赋值语句将值分配给存储位置。

以下语句将整数25分配给由变量示例表示的位置:

examples = 25;

=符号称为赋值运算符。

C++的一个特点是可以连续使用赋值运算符。

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

int a; 
int b; 
int c; 

a= b = c = 88; 

赋值从右到左工作。

第二个赋值语句表明您可以更改变量的值:

examples = examples - 1;  // modify the variable 

使用cin

以下代码使用cin(发音为“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; 
} 

上面的代码生成以下结果。

注意

以下语句读取值为变量。

cin >> examples;

iostream文件定义<< 操作符,以便您可以如下组合输出:

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

这允许您在单个语句中组合字符串输出和整数输出。

结果输出与以下代码生成的输出相同:

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; 
} 

上面的代码生成以下结果。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号