自学内容网 自学内容网

Dart常用数据类型

As we’ve seen, variables act as containers to store and recall data during program execution. However, to make sense of this data, the computer needs to know its type, just like you would distinguish between coins and paper notes in your Kolo (savings box). In Dart, data types help the computer understand the nature of the information stored in each variable, ensuring the integrity and reliability of the data.

正如我们所看到的,变量在程序执行期间充当存储和调用数据的容器。然而,为了理解这些数据,计算机需要知道它的类型,就像您在Kolo(储蓄箱)中区分硬币和纸币一样。在Dart中,数据类型帮助计算机理解存储在每个变量中的信息的性质,从而确保数据的完整性和可靠性。

Integer (int)

整数类型

In Dart, the integer data type represents whole numbers without any fractional or decimal parts. It allows you to work with numbers in a straightforward manner, just like counting objects or measuring quantities. Imagine you are managing a fruit stall, and you want to keep track of the number of oranges you have in stock. In Dart, you would use the ‘int’ data type to store this information.

在Dart中,整数数据类型表示没有任何小数部分的整数。它允许你以一种直接的方式处理数字,就像计算物体或测量数量一样。想象一下,您正在管理一个水果摊,并且您想要跟踪库存橙子的数量。在Dart中,您将使用’ int '数据类型来存储此信息。

Here’s how you can declare and use integers in Dart:

下面是如何在Dart中声明和使用整数:

int numberOfOranges = 50;

示例代码:

void main() {
  // 橘子的数量
  int numberOfOranges = 33;
  print(numberOfOranges);
}

输出:

33

In this example, we have declared a variable named numberOfOranges of type ‘int’ and assigned it a value of 50. Now, Dart understands that this variable should only store whole numbers and will raise an error if you try to assign a non-integer value to it.

在这个例子中,我们声明了一个名为“numberOfOranges”的变量,类型为“int”,并为其赋值50。现在,Dart知道这个变量应该只存储整数,如果您尝试给它赋一个非整数值,它将引发一个错误。

Integers come in various forms, such as positive and negative numbers, including zero. You can perform common mathematical operations like addition, subtraction, multiplication, and division with integer variables.

整数有多种形式,例如正数和负数,包括零。您可以对整数变量执行常见的数学运算,如加、减、乘和除。

int apples = 10;
int bananas = 5;
int totalFruits = apples + bananas; // totalFruits will be 15

示例代码:

void main() {
  int price = 33; // 单价
  int buyNum = 3; // 购买数量
  int totalPrice = price * buyNum; // 计算价格
  print(totalPrice);
}

输出:

99

You can also use integers to represent quantities, counts, and many other numeric aspects in your Dart programs. The integer data type is essential for a wide range of applications, from simple calculations to more complex algorithms.

您还可以在Dart程序中使用整数来表示数量、计数和许多其他数字方面。整数数据类型对于从简单计算到更复杂算法的广泛应用程序都是必不可少的。

Remember that Dart integers have a fixed size, which means they can represent a specific range of values based on their bit length. For example, a 32-bit integer can represent values from approximately -2 billion to +2 billion.

请记住,Dart整数具有固定的大小,这意味着它们可以根据其位长度表示特定的值范围。例如,一个32位整数可以表示大约从- 20亿到+ 20亿的值。

Double (double)

浮点数

The double data type is used to represent numbers with fractional parts. It’s ideal for dealing with values that require more precision, such as measurements, currency, or any real-world data that includes decimal points. Imagine you are working on a finance app, and you need to calculate the total amount due for a shopping cart. You would use the double data type to store the prices of items that may have fractions of a cent.

double数据类型用于表示带有小数部分的数字。它非常适合处理需要更高精度的值,例如测量值、货币或任何包含小数点的实际数据。假设你正在开发一个金融应用程序,你需要计算一个购物车的到期总额。您可以使用double数据类型来存储可能只有几分之一的商品的价格。

Here’s how you can declare and use double values in Dart:

下面是如何在Dart中声明和使用双精度值:

double priceOfItem = 49.99;

In this example, we’ve declared a variable named priceOfItem of type ‘double’ and assigned it a value of 49.99. Dart automatically recognizes this variable as a double, and you can perform various arithmetic operations with it, such as addition, subtraction, multiplication, and division.

在本例中,我们声明了一个名为“priceOfItem”的double类型变量,并为其赋值49.99。Dart自动将此变量识别为双精度,您可以使用它执行各种算术运算,例如加、减、乘和除。

double taxRate = 0.075;
double subtotal = 100.00;
double totalAmount = subtotal + (subtotal * taxRate); // totalAmount will be 107.50

示例代码:

void main() {
  double price = 33; // 单价
  double buyNum = 3; // 购买数量
  double totalPrice = price * buyNum; // 计算价格
  print(totalPrice);
}

输出:

99.0

Double values are particularly useful when handling realworld data that can be represented as fractions, percentages, or decimals. The double data type provides the precision needed for accurate calculations in these scenarios.

在处理可以表示为分数、百分比或小数的实际数据时,双精度值特别有用。在这些场景中,double数据类型提供了精确计算所需的精度。

It’s essential to be cautious when working with double values due to potential floating-point errors. These errors can arise from the internal representation of floating-point numbers in computers. Rounding errors can occur when you perform multiple arithmetic operations with double values. For critical financial calculations or scenarios where high precision is required, you may need to use additional techniques to mitigate floating-point errors.

由于潜在的浮点错误,在处理双精度值时必须谨慎。这些错误可能是由计算机中浮点数的内部表示引起的。当使用双精度值执行多个算术运算时,可能会出现舍入错误。对于关键的财务计算或需要高精度的场景,可能需要使用其他技术来减轻浮点错误。

String

字符串

The string data type is used to represent sequences of characters, such as text or words. Strings are essential for handling textual data, user inputs, messages, and much more. Imagine you are building a messaging app, and you need to store and display text messages between users. You would use the ‘String’ data type to handle these messages. Here’s how you can declare and use string values in Dart:

字符串数据类型用于表示字符序列,例如文本或单词。字符串对于处理文本数据、用户输入、消息等非常重要。假设您正在构建一个消息传递应用程序,并且需要在用户之间存储和显示文本消息。您将使用’ String '数据类型来处理这些消息。下面是如何在Dart中声明和使用字符串值:

String firstName = ‘John’;
String lastName = “Doe”;
String fullName = firstName + “ “ + lastName; // fullName will be “John Doe”

In this example, we’ve declared three variables, firstName, lastName, and fullName, all of type ‘String’. Dart allows you to create strings using single quotes or double quotes. You can concatenate strings using the ‘+’ operator to build more complex strings, as demonstrated by the fullName variable.

在这个例子中,我们声明了三个变量,firstName, lastName和fullName,它们的类型都是’ String ‘。Dart允许您使用单引号或双引号创建字符串。您可以使用’ + '操作符连接字符串以构建更复杂的字符串,fullName变量演示了这一点。

示例代码:

void main() {
  String a = "hello";
  String b = "world";
  String c = a + b;
  print(c);
}

输出:

helloworld

Strings can also contain special characters, escape sequences, and placeholders for dynamic values. Here’s an example of using an escape sequence to include a newline character in a string:

字符串还可以包含特殊字符、转义序列和动态值的占位符。下面是一个使用转义序列在字符串中包含换行字符的示例:

String message = “Hello, \nWelcome to our app!;

The ‘\n’ escape sequence inserts a new line in the string, resulting in the message being displayed with a line break. Moreover, you can use string interpolation to embed dynamic values within a string. Dart allows you to use the ‘$’ symbol, followed by the variable name inside a string, to include the value of the variable:

’ \n ‘转义序列在字符串中插入新行,导致消息以换行符显示。此外,您可以使用字符串插值在字符串中嵌入动态值。Dart允许你使用’ $ '符号,后跟字符串中的变量名,来包含变量的值:

int age = 30;
String greeting = “Hello, I am $age years old!;

In this case, the variable ‘age’ is embedded in the ‘greeting’ string, and its value will be dynamically inserted when the string is evaluated.

在这种情况下,变量’ age ‘被嵌入到’ greeting '字符串中,当字符串被求值时,它的值将被动态插入。

示例代码:

void main() {
  String name = "张大鹏";
  int age = 33;
  double height = 1.88;
  String info = "姓名:$name\n年龄:$age岁\n身高:$height米";
  print(info);
}

输出:

姓名:张大鹏
年龄:33岁
身高:1.88米

Boolean (bool)

布尔类型

The boolean data type is used to represent two values: true and false. Booleans are essential for making decisions in programming. They allow us to create conditions and control the flow of our code based on whether certain conditions are true or false.

布尔数据类型用于表示两个值:true和false。布尔值在编程决策中是必不可少的。它们允许我们创建条件,并基于某些条件是真还是假来控制代码流。

Imagine you are building a simple weather app, and you want to display a message depending on whether it’s sunny or rainy. You would use a boolean variable to represent the weather condition:

假设您正在构建一个简单的天气应用程序,并且希望根据晴天或雨天显示一条消息。你可以使用一个布尔变量来表示天气状况:

bool isSunny = true;
bool isRainy = false;

Here, we’ve declared two boolean variables, isSunny and isRainy. The true value in isSunny indicates that it’s sunny, while the false value in isRainy means it’s not raining.

在这里,我们声明了两个布尔变量,isSunny和isRainy。isSunny中的true值表示它是晴天,而isRainy中的false值表示它不是下雨。

Booleans are often used in conditional statements like if, else, and while to control the flow of code execution. Here’s an example of using a boolean variable in a simple if statement:

布尔值通常用于条件语句中,如’ if ', ’ else ‘和’ while ',以控制代码执行的流程。下面是一个在简单的if语句中使用布尔变量的例子:

void main() {
  bool isRaining = true;
  print(isRaining);
}

In this code, we display the value of the isRaining Boolean variable.

在这段代码中,我们显示了’ isRaining '布尔变量的值。

Boolean variables are useful in a wide range of scenarios, from simple decision-making to complex logic. Understanding how to work with boolean data types is essential for writing effective and dynamic Dart code that responds to changing conditions and user inputs.

布尔变量在从简单决策到复杂逻辑的各种场景中都很有用。了解如何使用布尔数据类型对于编写响应不断变化的条件和用户输入的有效动态Dart代码至关重要。

示例代码:

void main() {
  bool isSunny = true;
  bool isRainy = false;

  if (isSunny) {
    print("晴空万里!");
  }

  if (isRainy) {
    print("大雨瓢泼!");
  } else {
    print("没有下雨哦~");
  }
}

输出:

晴空万里!
没有下雨哦~

原文地址:https://blog.csdn.net/qq_37703224/article/details/142893231

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!