【问题标题】:I simply write a program to reverse a number but the output not meet my expectation [closed]我只是写了一个程序来反转一个数字,但输出不符合我的期望[关闭]
【发布时间】:2022-11-13 17:28:33
【问题描述】:
#include<iostream>
using namespace std;
class sample{
    int x,y;
    public:
    void rev();
};
void sample::rev(){
    cout<<"Enter a no:";
    cin>>x;
    int r,n;
    while(x!=0){
    r=x%10;
    n=n*10+r;
    x=x/10;
    }
    cout<<n;
}
int main(){
    sample A;
    A.rev();
    return 0;
}

如果我输入一个数字,如:10,它需要给我rev no:01,但它只给1......我该如何解决?

【问题讨论】:

标签: c++


【解决方案1】:

在您的代码中,这一行有问题:n=n*10+r;

由于n 没有被赋予初始值,因此右侧表达式的结果可能不是您认为的那样。

如前所述,整数类型不能有前导零。所以试图建立一个反向的int 是行不通的。

有很多方法可以做到这一点。不幸的是,您选择了一种行不通的方法。

首先想到的是递归。

#include <iostream>

void print_reversed(int n) {
  int next = n / 10;
  std::cout << n % 10;
  if (next != 0) {
    print_reversed(next);
  } else {
    std::cout << '
';
  }
}

int main() {
  int number;
  std::cout << "Input: ";
  std::cin >> number;

  print_reversed(number);
}

请注意,递归解决方案一次只打印一个数字。前导零不是问题。

或者,将输入作为字符串。

#include <algorithm>
#include <iostream>
#include <string>

int main() {
  std::string number;
  std::cout << "Input: ";
  std::getline(std::cin, number);

  /*
   * Ideally you would validate the string before continuing.
   */

  std::ranges::reverse(number);
  std::cout << number << '
';
}

std::ranges::reverse() 需要 C++20。您可以调用一个版本,它采用早期标准中的一对迭代器。

或者,将数字分解为数字并将它们存储在容器中以供打印。

#include <iostream>
#include <vector>

int main() {
  int number;
  std::cout << "Input: ";
  std::cin >> number;

  std::vector<int> digits;
  while (number != 0) {
    digits.push_back(number % 10);
    number /= 10;
  }

  for (auto i : digits) {
    std::cout << i;
  }
  std::cout << '
';
}

请注意,数字会以相反的顺序自动存储;拆开后不需要做任何事情。

我的偏好是递归解决方案,“输入为字符串”紧随其后。我不会真正使用第三种方法,但它仍然有效。

对于所有三种解决方案,如果我输入10,则打印输出为01

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2023-04-02
    • 2023-01-09
    • 2019-12-23
    • 2011-06-23
    • 2010-10-16
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    相关资源
    最近更新 更多