== 运算符与两个数组的名称来确定数组是否相等。以下代码似乎是在比较两个数组的内容,但实际上并不是。
int arrayA[] = { 5, 10, 15, 20, 25 };
int arrayB[] = { 5, 10, 15, 20, 25 };
if (arrayA == arrayB) // 语句错误
cout << "The arrays are the same. \n";
else
cout << "The arrays are not the same.\n";
在对数组名称使用 == 运算符时,运算符会比较数组的开始内存地址,而不是数组的内容。这个代码中的两个数组显然会有不同的内存地址。因此,表达式 arrayA == arrayB 的结果为 false,代码将报告数组不相同。
const int SIZE = 5;
int arrayA[SIZE] = { 5, 10, 15, 20, 25 };
int arrayB[SIZE] = { 5, 10, 15, 20, 25 };
bool arraysEqual = true; // 标志变量
int count = 0; //循环控制变量
//确定元素是否包含相同的数据
while (arraysEqual && count < SIZE)
{
if (arrayA[count] != arrayB[count])
arraysEqual = false;
count++;
}
//显示合适的消息
if (arraysEqual)
cout << "The arrays are equal.\n";
else
cout << "The arrays are not equal.\n";
此代码确定 arrayA 和 arrayB 是否包含相同的值。初始化为 true 的 bool 变量 arraysEqual 将表示数组是否相等。另一个初始化为 0 的变量 count 被用作循环计数器。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有