【问题标题】:this C++ code always gives same output这个 C++ 代码总是给出相同的输出
【发布时间】:2015-05-15 17:46:42
【问题描述】:

这是一个检查一个数和它的倒数是否相等的程序

#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 number\n";
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。 谁能帮我找出原因吗?

【问题讨论】:

  • 你的n变量没有初始化,从cin读取后移动n=num
  • 非常感谢。真是个愚蠢的错误。
  • 你在 while 循环中的步骤看起来不像我见过的任何“反转数字”的算法(你的意思是输入 '96' 应该给出输出 '69 '?) - 您是否尝试过使用调试器单步执行?
  • 顺便说一句。当您将输入作为字符串处理时,相反会更容易
  • 我现在已经试运行了,是的,你是对的,它没有提供所需的输出。它返回输入数字。为了使其工作,我需要知道如何计算数字中的数字编号,然后我可以修改我的算法并使其工作。

标签: c++ dev-c++


【解决方案1】:
#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
  int num;
  cout<<"Enter a number\n";
  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();   
} 

【讨论】:

  • 精彩,非常令人印象深刻。非常感谢。我正在努力,但我认为我不会只用三行就完成。
  • @farheen 很高兴为您提供帮助。请接受它作为答案。建议:在你做作业或学习的时候做一些文书工作,然后编码会容易得多。或者只是逐步调试您的程序。
  • 我会的。非常感谢您的建议。
  • 顺便说一句,你以前做过还是当场做过?我印象非常深刻。我真的很想成为一个非常好的程序员。我想我解决问题的能力还不错。如何我能成为一个聪明的程序员吗?
  • 这是一个简洁的解决方案(加一个),但@SmartDev 使用的循环非常惯用。都是有经验的。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2018-01-29
    • 1970-01-01
    相关资源
    最近更新 更多