dev 这C++代码始终提供相同的输出

dev this C++ code always gives same output

本文关键字:输出 C++ 代码 dev      更新时间:2023-10-16

这是一个程序,用于检查数字及其反向是否相等

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
 int num,n,digit,j,newNum;
 n=num;
 j=1;
 newNum=0;
cout<<"Enter a numbern";
cin>>num;
while(n>=1)
{
   digit=n%10;
n=n/10;
digit=digit*j;
newNum=newNum+digit;
j=j*10;        
}
  cout<<"The reverse of given number is:"<<newNum<<endl;
  if(num==newNum)
  cout<<"The given number and its reverse are equal";
  else
  cout<<"The given number and its reverse are not equal";
  getch();   
} 

'该程序接受一个数字作为输入,然后找到它的反向,然后检查反向是否等于数字。 每当我运行这个程序以及我作为输入给出的任何数字时,它都会给出相反的数字1975492148。 谁能帮我确定它的原因?

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
  int num;
  cout<<"Enter a numbern";
  cin>>num;
  int n = num;
  int rev = 0;
  while( n >= 1 )
  {
    int rem = n%10; 
    rev = (rev*10) + rem;
    n=n/10;
  }

  cout<<"The reverse of given number is:"<<rev<<endl;
  if(num==rev)
    cout<<"The given number and its reverse are equal" << endl;
  else
    cout<<"The given number and its reverse are not equal" << endl;
  getch();   
} 

赋值n=num;的行为未定义。这是因为此时尚未初始化num

然后,您将在程序的后面进一步使用n作为您的while条件。这不会有好下场。