反转数字C ++

时间:2015-10-08 22:50:46

标签: c++

在这里寻找一些关于我出错的建议。我主要的一切都应该没问题,保持不变。我的问题在于我的反向功能。它在“数字是”的cout语句之前打印反转的数字,而不是低于它应该的位置。我花了一段时间试图修复但无法提出解决方案。

 #include <iostream>
 #include <iomanip>
 #include <cstdlib>
 #include <ctime>
 using namespace std;

 const int NUM_VALS = 10;   //the maximum number of values to use

 int reverse(int num);
 bool isPrime(int num);

 int main()
  {
  int number,  //Holds the random number that is manipulated and tested
    loopCnt; //Controls the loop

  //set the seed value for the random number generator
  //Note: a value of 1 will generate the same sequence of "random" numbers     every
  //      time the program is executed
  srand(1);

  //Generate 10 random numbers to be manipulated and tested
  for( loopCnt = 1; loopCnt <= NUM_VALS; loopCnt++ )
       {
    //Get a random number
    number = rand();

   //Display the sum of adding up the digits in the random number, the reversed
   //random number, and whether or not the number is palindromic or a prime number

    cout << "The number is " << number << endl
         << "----------------------------------------" << endl
 //     << "Adding the digits result" << setw(16) << sumDigits( number ) << endl
        << "Reversing the digits result" << setw(13) << reverse(number) << endl
 //    << "Is the number a palindrome?" << setw(13) << (isPalindrome(number)? "Yes" : "No") << endl
 //     << "Is the number prime?" << setw(20) << (isPrime(number)? "Yes" : "No") << endl
        << endl << endl;
  }

  return 0;
}

int reverse(int num)
{
int quo, rem;
quo = num;  
while (quo != 0)
{
    rem = quo % 10;
    cout << rem;
    quo /= 10;
}

}

bool isPrime(int num)
{
int i;

if (num % 2 == 0)
    return false;
for (i = 3; i*i <= num; i+=2)
    {
        if (num % i == 0)
            return false;
    }
return true;
  }

2 个答案:

答案 0 :(得分:4)

您需要让reverse函数返回相反的数字,因为返回值在main中使用。

您可以通过乘以&#34;反转&#34;来构建反转数字。将值加10,然后加入余数:

int reverse(int num)
{
  int reversed = 0;
  int quo, rem;
  quo = num;  
  while (quo != 0)
  {
    rem = quo % 10;
    reversed = reversed * 10 + rem;
    quo /= 10;
  }
  return reversed;
}

答案 1 :(得分:0)

您也可以使用此方法通过输入字符串来反转数字,然后将其反转并将其转换为 int。

#include <iostream>
#include<string>

using namespace std;

int reverse_num(string a)
{
        string s;
        for(int i=a.length()-1;i>=0;i--)
        {
                s+=a[i];
        }
        int n;
        n=stoi(s);
        return n;
}
int main()
{
    
    string a;
    cin>> a;
    cout<<reverse_num(a);        
    return 0;
}