Logo
Section 1 / 5

C++中的变量

了解为什么我们的代码中需要变量,以及如何使用它们。

检查点

C++中的变量

了解为什么我们的代码中需要变量,以及如何使用它们。

...
1 / 3

接收用户输入前

1.

Suppose we want to write a program that displays the circumference of a circle. Let’s recall the formula for calculating the circumference of a circle:

2∗π∗r2∗π∗r

In this equation, which information remains the same (can be hardcoded), and which information changes for each circle (needs to be stored in a variable)?

0/500
1.

Identify the variables in the given sentence:

“I bought an animal, it was a duck and named it Daffy.”

0/500

代码示例

1<变量类型> <变量名>;

代码示例

1int age;

代码示例

1<变量名> = <值>;

1int age; 2age = 18;

代码示例

1int age = 18;

代码示例

1int age = 18; 2int year = 1998;

代码示例

1<变量类型> <变量1>, <变量2>, <变量3>;

代码示例

1int age = 18, year = 1998, month = 12;
...
1 / 4

变量声明

1#include <iostream> 2using namespace std; 3 4int main() { 5 int age = 18, month = 12; 6 cout << age; 7 cout << month; 8 return 0; 9}
1#include <iostream> 2using namespace std; 3 4int main() { 5 int age = 18, month = 12; 6 cout << age; 7 cout << endl; 8 cout << month; 9 return 0; 10}
1#include <iostream> 2using namespace std; 3 4int main() { 5 int age = 18, month = 12; 6 cout << age << " " << month << endl; 7 return 0; 8}

代码示例

1cout << 变量1 << 变量2 << 变量3;

可以使用 endl 添加换行符,对应代码如下:

1cout << age << endl << month;

可以使用 endl 添加换行符,对应代码如下:

1cout << age << endl << month;

代码示例

1int bodyTemp, bodytemp, BODYtemp;

推荐与不推荐使用的变量名

1int acc_bal; // 简洁但不够清晰,不是所有人都能理解 acc 和 bal 的含义 2int usersaccountbalance; // 变量名过长,难以阅读 3int userbal; // 可读性较差,使用下划线分隔会更清晰 4int xyz; // 变量名无意义 5int accountBalance; // 使用驼峰命名法,语义明确且易于阅读

Quiz

多选题

(选择所有适用项。)找出以下代码中的错误:

1init test = p; 2cout << Test << " ";
1 / 3

简介

变量类型