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

问题描述 投票:0回答:1

我应该提一下此代码的目的是解决在以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]再次……让我感到困惑。

c++ arrays if-statement
1个回答
0
投票

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

第二个循环写之前

number = date;
© www.soinside.com 2019 - 2024. All rights reserved.