c++ - 为什么两个相同数组的元素彼此相等

标签 c++ arrays if-statement

我应该提到的是,此代码的目的是在以MMDDYYY格式的日期查找日期回文时解决前导零情况。

这是代码。

#include <iostream>
using namespace std;
unsigned numDigits (unsigned num)//this works
{
  if (num < 10) return 1;
  return 1+ numDigits(num/10);
}

int main ()
{
  unsigned date = 1111110;//01/11/1110(jan 11th of 1110 is palindrome)
  cout<<numDigits(date)<<"num of dig"<<endl;

  if (numDigits(date) == 7)
  { 
    unsigned array[8];
    unsigned number = date;
    unsigned revArr[8];

    for (int h = 7; h >= 0; h--) //this pops array withdate
    {
      array[h] = number % 10;
      number /= 10;
      cout<<array[h]<<endl;
    }
    cout<<"vs"<<endl;

    for (int i = 0; i < 8; i++) //this pops revarray withdate
    {
    revArr[i] = number % 10;
    number /= 10;
    cout<<array[i]<<endl;
    }


    for (int j = 0; j < 8; j++)
    {
      if (array[j] == revArr[j])
      {
        cout<<j<<"th digit are" <<" equal"<<endl;
      }
    }

   }
  return 0;
}  

在这种情况下,两个数组都是相同的,我不理解为什么array [0] == revArr [0]但是array [1]!= revArr [1]等等,但array [7] == revArr [7 ]再次...令人困惑。

最佳答案

循环遍历数组的所有元素。即使表达式number /= 100相等。在这种情况下,零被存储在数组元素中,因为0 / 10再次给出0

在第二个循环之前写

number = date;

关于c++ - 为什么两个相同数组的元素彼此相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60142310/

相关文章:

c++ - 通过编码在 C++ 中查找 Debug 或 Release 模式

javascript - javascript for 循环不是每次都执行的问题

javascript - 在多维数组中查找 int 并在 Angular JS 中应用类

javascript - 如何在Interval React.js中乘以数字时获得索引0

c++ - 使用 goto 来避免深层函数调用中的堆栈溢出是个好主意吗?

c++ - 堆栈展开对析构函数的调用

python - 获取 Numpy 二维数组相交行的索引

c# 条件语句 |

r - 如何创建一个返回 2 个整数之和的函数?

c++ - 存储霍夫曼树的有效方法