反向数字程序不起作用,为什么?

问题描述 投票:-1回答:3
#include <iostream>

using namespace std;
int main()
{

  int n,sum=0;
  cout<<"enter no.";
  cin>>n;

  while(n!=0)
  {
      int r=n%10;
      int sum= (sum*10)+r;
      n=n/10;
  }
cout<<sum;
return 0;

}

这里的输出应该反转一个数字,但它的o / p为'0'不懂你!!请帮助。

c++ numbers reverse
3个回答
4
投票

您的代码基本上是正确的,但是您在while循环中犯了一个小错误。旧代码:-

#include <iostream>

using namespace std;
int main()
{

  int n,sum=0;
  cout<<"enter no.";
  cin>>n;

  while(n!=0)
  {
      int r=n%10;         //-- Y R U declaring the variables 'r' and 'sum' here?
      int sum= (sum*10)+r;//-- Declare them at top and initialize 'sum' with 0
      n=n/10;
  }
cout<<sum;
return 0;

}

新代码:-

#include <iostream>
using namespace std;
int main()
{
    int n, sum = 0;
    cout << "Enter a number >> ";
    cin >> n;

    while (n != 0) {
        sum = (sum * 10) + n % 10;
        n /= 10;
    }
    cout << sum << endl;
    return EXIT_SUCCESS;
}

输出:-

Enter a number >> 123456
654321
Press any key to continue . . . _

0
投票

不读数字,不读字符串:

#include <iostream>

using namespace std;
int main()
{

  std::string n;
  cout<<"enter no.";
  cin>>n;

  std::string reversed(n.rbegin(), n.rend());

  cout<<reversed;

  return 0;
}

0
投票

问题是int之前的sum在循环内部创建了一个隐藏外部sum的局部变量。如果删除它,则程序将运行。您可能想在scoping中查找C ++变量。

#include <iostream>

using namespace std;
int main()
{

  int n,sum=0;
  cout<<"enter no.";
  cin>>n;

  while(n!=0)
  {
      int r = n % 10;
      sum = (sum * 10) + r;
      //^^ note no int
      n=n/10;
  }
  cout<<sum;
  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.