【发布时间】:2020-02-09 23:20:22
【问题描述】:
我应该提到此代码的目的是在以 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 /= 10;的变异号码。制作数字的临时副本并在循环中使用它 -
谢谢。是的,添加变量“number”的副本并使用它来填充 'revArr[];'解决了我的问题。
标签: c++ arrays if-statement