如何反转实数的数字

how to reverse digits of a real no?

本文关键字:数字 实数 何反转      更新时间:2023-10-16

我知道在c中反转一个数字(整数)的数字,但我的问题是我们如何反转一个实数的数字例如,1200.23被反转为32.0021

整数代码

#include <stdio.h>
/* Iterative function to reverse digits of num(integer)*/
int reversDigits(int num) 
{
  int rev_num = 0;
  while(num > 0)
  {
    rev_num = rev_num*10 + num%10;
    num = num/10;
  }
  return rev_num;
}
/*Driver program to test reversDigits*/
int main()
{
  int num = 4562;
  printf("Reverse of no. is %d", reversDigits(num));
  getchar();
  return 0;
}

显然你的参数需要是浮点类型。

你可以将double型转换成string型,然后将string型转换回double型:

#include <string>
#include <sstream>
template<typename T>
std::string toString(T t)
{
    std::stringstream ss;
    ss << t;
    rteurn ss.str();
}
double reversDigits(double num)
{
    std::string s = std::to_string(num);
    std::reverse(s.begin(), s.end());

    double d;
    std::stringstream ss(s);
    ss >> d;
    return d;
}

您可以使用以下代码,其中使用了iostream库:

#include <iostream>
#include <math.h>
using namespace std;
int main() {
    double pass = 0;
    double n;
    double result=0;
    cout << "Please enter a number to reverse" << endl;
    cin >> n;
    while (trunc(n / pow(10.0, pass)) > 0) {
        result = fmod((n / pow(10.0, pass)), 10.0);
        cout << trunc(result);
        pass = pass + 1;
    }
    cout << endl;
    system("pause");
    return 0;
}

使用方法(12345/10),得到1234.5,然后截断为1234。上面的代码还使用了modulo方法('%'是取模的运算符)。例如,如果执行12345 % 10,程序将显示12345/10的余数,在本例中为5。

我在一个循环中使用这个方法来获得所需的输出。

请注意,我为一个类编写了这个程序,所以如果这不是你想要的,请忽略这篇文章。

试试这个代码-

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
float reversDigits(float num)
{
  char buffer[20],ch,*ptr;
  int i,j,len;
  snprintf(buffer,20,"%.3lf",num);
  len = strlen(buffer);
  for(i=0,j=len-1;i<j;i++,j--)
  {
        ch=buffer[i];
        buffer[i]=buffer[j];
        buffer[j]=ch;
  }
  buffer[len] = '';
  return atof(buffer);
}
int main()
{
  float num = 45000.062;
  printf("Reverse of no. is %.5lfn", reversDigits(num));
  return 0;
}

我在.之后传递一个3位数的数字,所以我在snprintf中使用%.3lf,如果你简单地使用%lf意味着,在将其转换为字符串的同时,它将添加零和一些数字。为了避免我使用,否则你需要做一点更多的工作来删除它!

注意:当将string转换为float或float转换为string时,它会在小数点后加一些额外的数字或零。程序员需要照顾它!